blob: ebb47efe19a2090fc5d92a1d780b06b292a351ab [file] [log] [blame]
Hyunsun Moon6ff622e2020-03-11 17:14:48 -07001# vim: syntax=py
2# -*- mode: python -*-
3# SPDX-License-Identifier: Apache-2.0
4# Copyright 2020-present Open Networking Foundation
5# Copyright(c) 2019 Intel Corporation
6
7# for errnos
8import errno
9from conf.utils import *
10
11
12# ====================================================
13# Parameters
14# ====================================================
15
16
17conf_file = get_env('CONF_FILE', 'conf/spgwu.json')
18conf = get_json_conf(conf_file, False)
19
20# Maximum number of flows to manage ip frags for re-assembly
21max_ip_defrag_flows = None
22try:
23 max_ip_defrag_flows = int(conf["max_ip_defrag_flows"])
24except ValueError:
25 print('Invalid value for max_ip_defrag_flows. Not installing IPDefrag module.')
26except KeyError:
27 print('max_ip_defrag_flows value not set. Not installing IPDefrag module.')
28
29# ====================================================
30# Port Helpers
31# ====================================================
32
33
34MAX_GATES = 8192
35dpdk_ports = {}
36
37
38def scan_dpdk_ports():
39 idx = 0
40 while True:
41 try:
42 intf = PMDPort(name="Port {}".format(idx), port_id=idx)
43 if intf:
44 # Need to declare mac so that we don't lose key during destroy_port
45 mac = intf.mac_addr
46 dpdk_ports[mac] = idx
47 bess.destroy_port(intf.name)
48 except bess.Error as e:
49 if e.code == errno.ENODEV:
50 break
51 else:
52 raise
53 idx += 1
54 return True if dpdk_ports else False
55
56
57class Port:
58 def __init__(self, name):
59 self.name = name
60 self.wid = None
61 self.fpi = None
62 self.fpo = None
63 self.bpf = None
64 self.bpfgate = 0
65 self.routes_table = None
66
67 def bpf_gate(self):
68 if self.bpfgate < MAX_GATES - 2:
69 self.bpfgate += 1
70 return self.bpfgate
71 else:
72 raise Exception('Port {}: Out of BPF gates to allocate'.format(self.name))
73
74 def detect_mode(self):
75 # default case
76 mode = "unselected"
77
78 try:
79 peer_by_interface(self.name)
80 mode = "dpdk"
81 except:
82 mode = "linux"
83 return mode
84
85 def init_fastpath(self, **kwargs):
86 # Initialize PMDPort and RX/TX modules
87 name = self.name
88 fast = PMDPort(name="{}Fast".format(name), **kwargs)
89 self.fpi = __bess_module__("{}FastPI".format(name), 'PortInc', port=fast.name)
90 self.fpo = __bess_module__("{}FastPO".format(name), 'PortOut', port=fast.name)
91
92 # Initialize BPF to classify incoming traffic to go to kernel and/or pipeline
93 self.bpf = __bess_module__("{}FastBPF".format(name), 'BPF')
94 self.bpf.clear()
95
96 # Default drop when no matches
97 if max_ip_defrag_flows is not None:
98 ipdefrag = __bess_module__("{}Defrag".format(name), 'IPDefrag', num_flows=max_ip_defrag_flows, numa=0)
99 self.fpi -> ipdefrag:1 -> self.bpf:0 -> Sink()
100 ipdefrag:0 -> Sink()
101 else:
102 self.fpi -> self.bpf:0 -> Sink()
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
173 tc = 'slow{}'.format(wid)
174 try:
175 bess.add_tc(tc, policy='round_robin', wid=wid)
176 except Exception as e:
177 if e.errmsg == "Name '{}' already exists".format(tc):
178 pass
179 else:
180 raise e
181 # Limit scheduling slow path RX/TX to 1000 times/second each
182 for mod in spi, qspo:
183 bess.add_tc(mod.name,
184 parent=tc,
185 policy='rate_limit',
186 resource='count',
187 limit={'count': 1000})
188 mod.attach_task(mod.name)
189 except Exception as e:
190 print('Mirror veth interface: {} misconfigured: {}'.format(name, e))
191 else:
192 raise Exception('Invalid mode selected.')
193
194
195# ====================================================
196# Validate
197# ====================================================
198
199
200# CIDRs
201enb_cidr = conf["enb_cidr"]
202ue_cidr = conf["ue_cidr"]
203
204cidrs = [enb_cidr, ue_cidr]
205for cidr in cidrs:
206 if validate_cidr(cidr) is False:
207 exit(1, 'Invalid {}'.format(cidr))
208
209# ====================================================
210# Core Setup
211# ====================================================
212
213
214# Initialize workers
215workers = 1
216try:
217 workers = int(conf["workers"])
218except ValueError:
219 print('Invalid workers value! Re-setting # of workers to 1.')
220
221cores = get_process_affinity()
222for wid in xrange(workers):
223 bess.add_worker(wid=wid, core=int(cores[wid % len(cores)]))
224
225# ====================================================
226# Port Setup
227# ====================================================
228
229
230interfaces = ["s1u", "sgi"]
231ports = {}
232for idx, interface in enumerate(interfaces):
233 port = Port(conf[interface]["ifname"])
234 if port.name in ports:
235 continue
236 port.setup_port(idx, workers)
237 ports[port.name] = port
238
239s1u_ifname = conf["s1u"]["ifname"]
240sgi_ifname = conf["sgi"]["ifname"]
241
242# ====================================================
243# Downlink Pipeline
244# ====================================================
245
246s1uRoutes = ports[s1u_ifname].rtr
247
248# Maximum number of sessions to manage
249try:
250 max_sessions = int(conf["max_sessions"])
251except ValueError:
252 print('Invalid max_sessions value!')
253
254# Setting filter to detect UE subnet
255sgiFastBPF = ports[sgi_ifname].bpf
256UEGate = ports[sgi_ifname].bpf_gate()
257ue_filter = {"priority": -UEGate,
258 "filter": "ip dst net {}".format(ue_cidr), "gate": UEGate}
259sgiFastBPF.add(filters=[ue_filter])
260
261sgiFastBPF:UEGate \
262 -> EtherTrim::GenericDecap(bytes=14) \
263 -> GTPUEncap::GtpuEncap(s1u_sgw_ip=ip2long(ips_by_interface(s1u_ifname)[0]), num_subscribers=max_sessions):1 \
264 -> S1UEtherAdd::GenericEncap(fields=[
265 {'size': 6, 'value': {'value_int': 0x0}},
266 {'size': 6, 'value': {'value_int': mac2hex(mac_by_interface(s1u_ifname))}},
267 {'size': 2, 'value': {'value_int': 0x0800}}]) \
268 -> OuterUDPCsum::L4Checksum() \
269 -> OuterIPCsum::IPChecksum() \
270 -> s1uRoutes
271
272# Drop unknown packets
273GTPUEncap:0 -> Sink()
274
275
276# ====================================================
277# Uplink Pipeline
278# ====================================================
279
280
281# Setting filter to detect gtpu traffic
282# src net 11.1.1.0 mask 255.255.255.0 # check eNB subnet
283# and dst host 11.1.1.1 # check S/PGWU IP
284# and udp dst port 2152 # check GTPU port
285# and (udp[28:4] & 0xffffff00) = 0x10000000 # check UE subnet
286s1uFastBPF = ports[s1u_ifname].bpf
287check_enb_subnet = "src net {} ".format(enb_cidr)
288check_spgwu_ip = " and dst host " + \
289 " or ".join(str(x) for x in ips_by_interface(s1u_ifname))
290check_gtpu_port = " and udp dst port 2152"
291check_ue_subnet = " and (udp[28:4] & 0x{}) = 0x{}".format(
292 cidr2mask(ue_cidr), ip2hex(cidr2block(ue_cidr)[0]))
293check_gtpu_msg_echo = " and udp[9] = 0x1"
294
295GTPUEchoGate = ports[s1u_ifname].bpf_gate()
296uplink_echo_filter = {"priority": -GTPUEchoGate, "filter": check_enb_subnet +
297 check_spgwu_ip + check_gtpu_port +
298 check_gtpu_msg_echo, "gate": GTPUEchoGate}
299s1uFastBPF.add(filters=[uplink_echo_filter])
300
301GTPUGate = ports[s1u_ifname].bpf_gate()
302uplink_filter = {"priority": -GTPUGate, "filter": check_enb_subnet +
303 check_spgwu_ip + check_gtpu_port, "gate": GTPUGate}
304s1uFastBPF.add(filters=[uplink_filter])
305
306sgiRoutes = ports[sgi_ifname].rtr
307
308s1uFastBPF:GTPUGate -> EtherDecapTrim::GenericDecap(bytes=14) -> GTPUDecap::GtpuDecap(ename="GTPUEncap"):1 \
309 -> SGIEtherAdd::GenericEncap(fields=[
310 {'size': 6, 'value': {'value_int': 0x0}},
311 {'size': 6, 'value': {'value_int': mac2hex(mac_by_interface(sgi_ifname))}},
312 {'size': 2, 'value': {'value_int': 0x0800}}]) \
313 -> sgiRoutes
314
315s1uFastBPF:GTPUEchoGate \
316 -> GTPUEcho::GtpuEcho(s1u_sgw_ip=ip2long(ips_by_interface(s1u_ifname)[0])):1 \
317 -> EthSwap::MACSwap() \
318 -> 1:OuterUDPCsum
319
320# Drop unknown packets
321GTPUEcho:0 -> Sink()
322GTPUDecap:0 -> Sink()
323
324
325# ====================================================
326# SIM_TEST
327# ====================================================
328
329import time
330
331def sim_start_test():
332 start_teid = 0xf0000000
333 start_ue_ip = 0x10000001
334 start_enb_ip = 0x0b010181
335 NG4T_MAX_UE_RAN = 500000
336 NG4T_MAX_ENB_RAN = 80
337
338 for i in range(max_sessions):
339
340 # NG4T-based formula to calculate enodeB IP address against a given UE IP address
341 # il_trafficgen also uses the same scheme
342 # See SimuCPEnbv4Teid(...) in ngic code for more details
343 ue_of_ran = i % NG4T_MAX_UE_RAN
344 ran = i / NG4T_MAX_UE_RAN
345 enb_of_ran = ue_of_ran % NG4T_MAX_ENB_RAN
346 enb_idx = ran * NG4T_MAX_ENB_RAN + enb_of_ran
347
348 GTPUEncap.add(teid=start_teid+i, eteid=i+1, ueaddr=start_ue_ip+i, enodeb_ip=start_enb_ip+enb_idx)
349
350def sim_end_test():
351 start_ue_ip = 0x10000001
352
353 for i in range(max_sessions):
354 GTPUEncap.remove(ueaddr=start_ue_ip+i)
355
356 GTPUEncap.show_records()
357
358### Uncomment the following lines to test with il_trafficgen ###
359# Start the test
360#sim_start_test()
361# Wait for 30 seconds before deleting the session info entries (optional)
362#time.sleep(30)
363#sim_end_test()
364
365# Finally send SIGHUP to route_control daemon on reload
366# TODO: behavior is unspecified if route_control.py pid is not found
367route_control_pid = getpythonpid('route_control.py')
368if route_control_pid:
369 os.kill(route_control_pid, signal.SIGHUP)