blob: f716a630cf19731dc3980f5d29c940f2f81538ec [file] [log] [blame]
Carmelo Casconea62ac3d2017-08-30 03:19:00 +02001/*
2 * Copyright 2017-present Open Networking Foundation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package org.onosproject.drivers.p4runtime;
18
19import com.google.common.collect.ImmutableBiMap;
20import com.google.common.collect.ImmutableList;
Ray Milkeyf0c47612017-09-28 11:29:38 -070021import org.onlab.packet.DeserializationException;
Carmelo Casconea62ac3d2017-08-30 03:19:00 +020022import org.onlab.packet.Ethernet;
23import org.onlab.util.ImmutableByteSequence;
24import org.onosproject.net.ConnectPoint;
25import org.onosproject.net.DeviceId;
26import org.onosproject.net.Port;
27import org.onosproject.net.PortNumber;
28import org.onosproject.net.device.DeviceService;
29import org.onosproject.net.driver.AbstractHandlerBehaviour;
30import org.onosproject.net.flow.TrafficTreatment;
31import org.onosproject.net.flow.criteria.Criterion;
32import org.onosproject.net.flow.instructions.Instruction;
33import org.onosproject.net.flow.instructions.Instructions;
Yi Tseng82512da2017-08-16 19:46:36 -070034import org.onosproject.net.flow.instructions.PiInstruction;
Carmelo Casconea62ac3d2017-08-30 03:19:00 +020035import org.onosproject.net.packet.DefaultInboundPacket;
36import org.onosproject.net.packet.InboundPacket;
37import org.onosproject.net.packet.OutboundPacket;
38import org.onosproject.net.pi.model.PiHeaderFieldModel;
39import org.onosproject.net.pi.model.PiPipeconf;
40import org.onosproject.net.pi.model.PiPipeconfId;
41import org.onosproject.net.pi.model.PiPipelineInterpreter;
42import org.onosproject.net.pi.model.PiPipelineModel;
43import org.onosproject.net.pi.model.PiTableModel;
44import org.onosproject.net.pi.runtime.PiAction;
45import org.onosproject.net.pi.runtime.PiActionId;
46import org.onosproject.net.pi.runtime.PiActionParam;
47import org.onosproject.net.pi.runtime.PiActionParamId;
Carmelo Cascone7f75be42017-09-07 14:37:02 +020048import org.onosproject.net.pi.runtime.PiCounterId;
49import org.onosproject.net.pi.runtime.PiCounterType;
Carmelo Casconea62ac3d2017-08-30 03:19:00 +020050import org.onosproject.net.pi.runtime.PiHeaderFieldId;
51import org.onosproject.net.pi.runtime.PiPacketMetadata;
52import org.onosproject.net.pi.runtime.PiPacketMetadataId;
53import org.onosproject.net.pi.runtime.PiPacketOperation;
54import org.onosproject.net.pi.runtime.PiPipeconfService;
55import org.onosproject.net.pi.runtime.PiTableId;
56
57import java.nio.ByteBuffer;
58import java.util.Collection;
59import java.util.List;
60import java.util.Optional;
61
62import static java.lang.String.format;
63import static java.util.stream.Collectors.toList;
64import static org.onlab.util.ImmutableByteSequence.copyFrom;
65import static org.onlab.util.ImmutableByteSequence.fit;
66import static org.onosproject.net.PortNumber.CONTROLLER;
67import static org.onosproject.net.PortNumber.FLOOD;
68import static org.onosproject.net.flow.instructions.Instruction.Type.OUTPUT;
69import static org.onosproject.net.pi.runtime.PiPacketOperation.Type.PACKET_OUT;
70
71/**
72 * Implementation of an interpreter that can be used for any P4 program based on default.p4 (i.e. those under
73 * onos/tools/test/p4src).
74 */
75public class DefaultP4Interpreter extends AbstractHandlerBehaviour implements PiPipelineInterpreter {
76
77 // FIXME: Should move this class out of the p4runtime drivers.
78 // e.g. in a dedicated onos/pipeconf directory, along with any related P4 source code.
79
80 public static final String TABLE0 = "table0";
Carmelo Cascone7f75be42017-09-07 14:37:02 +020081 public static final String TABLE0_COUNTER = "table0_counter";
Yi Tsenga87b40c2017-09-10 00:59:03 -070082 public static final String ECMP = "ecmp";
Carmelo Casconea62ac3d2017-08-30 03:19:00 +020083 public static final String SEND_TO_CPU = "send_to_cpu";
84 public static final String PORT = "port";
Carmelo Casconeeb018122017-09-06 13:16:03 +020085 public static final String DROP = "_drop";
Carmelo Casconea62ac3d2017-08-30 03:19:00 +020086 public static final String SET_EGRESS_PORT = "set_egress_port";
87 public static final String EGRESS_PORT = "egress_port";
88 public static final String INGRESS_PORT = "ingress_port";
89
Carmelo Cascone7f75be42017-09-07 14:37:02 +020090 private static final PiTableId TABLE0_ID = PiTableId.of(TABLE0);
Yi Tsenga87b40c2017-09-10 00:59:03 -070091 private static final PiTableId ECMP_ID = PiTableId.of(ECMP);
Carmelo Cascone7f75be42017-09-07 14:37:02 +020092
Carmelo Casconea62ac3d2017-08-30 03:19:00 +020093 protected static final PiHeaderFieldId ETH_DST_ID = PiHeaderFieldId.of("ethernet", "dstAddr");
94 protected static final PiHeaderFieldId ETH_SRC_ID = PiHeaderFieldId.of("ethernet", "srcAddr");
95 protected static final PiHeaderFieldId ETH_TYPE_ID = PiHeaderFieldId.of("ethernet", "etherType");
96
97 private static final ImmutableBiMap<Integer, PiTableId> TABLE_MAP = ImmutableBiMap.of(
Yi Tsenga87b40c2017-09-10 00:59:03 -070098 0, TABLE0_ID,
99 1, ECMP_ID);
Carmelo Cascone7f75be42017-09-07 14:37:02 +0200100
101 private static final ImmutableBiMap<PiTableId, PiCounterId> TABLE_COUNTER_MAP = ImmutableBiMap.of(
102 TABLE0_ID, PiCounterId.of(TABLE0_COUNTER, PiCounterType.DIRECT));
Carmelo Casconea62ac3d2017-08-30 03:19:00 +0200103
104 private boolean targetAttributesInitialized = false;
105
106 /*
107 The following attributes are target-specific, i.e. they might change from one target to another.
108 */
109 private ImmutableBiMap<Criterion.Type, PiHeaderFieldId> criterionMap;
110 private int portFieldBitWidth;
111
112 /**
113 * Populates target-specific attributes based on this device's pipeline model.
114 */
115 private synchronized void initTargetSpecificAttributes() {
116 if (targetAttributesInitialized) {
117 return;
118 }
119
120 DeviceId deviceId = this.handler().data().deviceId();
121 PiPipeconfService pipeconfService = this.handler().get(PiPipeconfService.class);
122 PiPipeconfId pipeconfId = pipeconfService.ofDevice(deviceId)
123 .orElseThrow(() -> new RuntimeException(format(
124 "Unable to get current pipeconf for device %s", this.data().deviceId())));
125 PiPipeconf pipeconf = pipeconfService.getPipeconf(pipeconfId)
126 .orElseThrow(() -> new RuntimeException(format(
127 "Pipeconf %s is not registered", pipeconfId)));
128 PiPipelineModel model = pipeconf.pipelineModel();
129
130 this.portFieldBitWidth = extractPortFieldBitWidth(model);
131 this.criterionMap = new ImmutableBiMap.Builder<Criterion.Type, PiHeaderFieldId>()
132 .put(Criterion.Type.IN_PORT, extractInPortFieldId(model))
133 .put(Criterion.Type.ETH_DST, ETH_DST_ID)
134 .put(Criterion.Type.ETH_SRC, ETH_SRC_ID)
135 .put(Criterion.Type.ETH_TYPE, ETH_TYPE_ID)
136 .build();
137
138 this.targetAttributesInitialized = true;
139 }
140
141 private static PiHeaderFieldId extractInPortFieldId(PiPipelineModel model) {
142 /*
143 For the targets we currently support, the field name is "ingress_port", but we miss the header name, which is
144 target-specific. We know table0 defines that field as a match key, we look for it and we get the header name.
145 */
146 PiTableModel tableModel = model.table(TABLE0).orElseThrow(() -> new RuntimeException(format(
147 "No such table '%s' in pipeline model", TABLE0)));
148 PiHeaderFieldModel fieldModel = tableModel.matchFields().stream()
149 .filter(m -> m.field().type().name().equals(INGRESS_PORT))
150 .findFirst()
151 .orElseThrow(() -> new RuntimeException(format(
152 "No such match field in table '%s' with name '%s'", TABLE0, INGRESS_PORT)))
153 .field();
154 return PiHeaderFieldId.of(fieldModel.header().name(), INGRESS_PORT);
155 }
156
157 private static int extractPortFieldBitWidth(PiPipelineModel model) {
158 /*
159 Get it form the set_egress_port action parameters.
160 */
161 return model
162 .action(SET_EGRESS_PORT).orElseThrow(() -> new RuntimeException(format(
163 "No such action '%s' in pipeline model", SET_EGRESS_PORT)))
164 .param(PORT).orElseThrow(() -> new RuntimeException(format(
165 "No such parameter '%s' of action '%s' in pipeline model", PORT, SET_EGRESS_PORT)))
166 .bitWidth();
167 }
168
169
170 @Override
171 public PiAction mapTreatment(TrafficTreatment treatment, PiTableId piTableId) throws PiInterpreterException {
Yi Tseng82512da2017-08-16 19:46:36 -0700172 initTargetSpecificAttributes();
Carmelo Casconea62ac3d2017-08-30 03:19:00 +0200173 if (treatment.allInstructions().size() == 0) {
174 // No instructions means drop for us.
175 return actionWithName(DROP);
176 } else if (treatment.allInstructions().size() > 1) {
177 // Otherwise, we understand treatments with only 1 instruction.
178 throw new PiPipelineInterpreter.PiInterpreterException("Treatment has multiple instructions");
179 }
180
181 Instruction instruction = treatment.allInstructions().get(0);
182
183 switch (instruction.type()) {
184 case OUTPUT:
185 Instructions.OutputInstruction outInstruction = (Instructions.OutputInstruction) instruction;
Yi Tseng82512da2017-08-16 19:46:36 -0700186 return outputPiAction(outInstruction);
187 case PROTOCOL_INDEPENDENT:
188 PiInstruction piInstruction = (PiInstruction) instruction;
189 return (PiAction) piInstruction.action();
Carmelo Casconea62ac3d2017-08-30 03:19:00 +0200190 case NOACTION:
191 return actionWithName(DROP);
192 default:
193 throw new PiInterpreterException(format("Instruction type '%s' not supported", instruction.type()));
194 }
195 }
196
Yi Tseng82512da2017-08-16 19:46:36 -0700197 private PiAction outputPiAction(Instructions.OutputInstruction outInstruction) throws PiInterpreterException {
198 PortNumber port = outInstruction.port();
199 if (!port.isLogical()) {
200 try {
201 return PiAction.builder()
202 .withId(PiActionId.of(SET_EGRESS_PORT))
203 .withParameter(new PiActionParam(PiActionParamId.of(PORT),
204 fit(copyFrom(port.toLong()), portFieldBitWidth)))
205 .build();
206 } catch (ImmutableByteSequence.ByteSequenceTrimException e) {
207 throw new PiInterpreterException(e.getMessage());
208 }
209 } else if (port.equals(CONTROLLER)) {
210 return actionWithName(SEND_TO_CPU);
211 } else {
212 throw new PiInterpreterException(format("Egress on logical port '%s' not supported", port));
213 }
214 }
215
Carmelo Casconea62ac3d2017-08-30 03:19:00 +0200216 @Override
Carmelo Cascone7f75be42017-09-07 14:37:02 +0200217 public Optional<PiCounterId> mapTableCounter(PiTableId piTableId) {
218 return Optional.ofNullable(TABLE_COUNTER_MAP.get(piTableId));
219 }
220
221 @Override
Carmelo Casconea62ac3d2017-08-30 03:19:00 +0200222 public Collection<PiPacketOperation> mapOutboundPacket(OutboundPacket packet)
223 throws PiInterpreterException {
224 TrafficTreatment treatment = packet.treatment();
225
226 // default.p4 supports only OUTPUT instructions.
227 List<Instructions.OutputInstruction> outInstructions = treatment.allInstructions()
228 .stream()
229 .filter(i -> i.type().equals(OUTPUT))
230 .map(i -> (Instructions.OutputInstruction) i)
231 .collect(toList());
232
233 if (treatment.allInstructions().size() != outInstructions.size()) {
234 // There are other instructions that are not of type OUTPUT.
235 throw new PiInterpreterException("Treatment not supported: " + treatment);
236 }
237
238 ImmutableList.Builder<PiPacketOperation> builder = ImmutableList.builder();
239 for (Instructions.OutputInstruction outInst : outInstructions) {
240 if (outInst.port().isLogical() && !outInst.port().equals(FLOOD)) {
241 throw new PiInterpreterException(format("Output on logical port '%s' not supported", outInst.port()));
242 } else if (outInst.port().equals(FLOOD)) {
243 // Since default.p4 does not support flooding, we create a packet operation for each switch port.
244 for (Port port : handler().get(DeviceService.class).getPorts(packet.sendThrough())) {
245 builder.add(createPiPacketOperation(packet.data(), port.number().toLong()));
246 }
247 } else {
248 builder.add(createPiPacketOperation(packet.data(), outInst.port().toLong()));
249 }
250 }
251 return builder.build();
252 }
253
254 @Override
255 public InboundPacket mapInboundPacket(DeviceId deviceId, PiPacketOperation packetIn)
256 throws PiInterpreterException {
257 // Assuming that the packet is ethernet, which is fine since default.p4 can deparse only ethernet packets.
Ray Milkeyf0c47612017-09-28 11:29:38 -0700258 Ethernet ethPkt;
259 try {
260 ethPkt = Ethernet.deserializer().deserialize(packetIn.data().asArray(), 0, packetIn.data().size());
261 } catch (DeserializationException dex) {
262 throw new PiInterpreterException(dex.getMessage());
263 }
Carmelo Casconea62ac3d2017-08-30 03:19:00 +0200264
265 // Returns the ingress port packet metadata.
266 Optional<PiPacketMetadata> packetMetadata = packetIn.metadatas()
267 .stream().filter(metadata -> metadata.id().name().equals(INGRESS_PORT))
268 .findFirst();
269
270 if (packetMetadata.isPresent()) {
271 ImmutableByteSequence portByteSequence = packetMetadata.get().value();
272 short s = portByteSequence.asReadOnlyBuffer().getShort();
273 ConnectPoint receivedFrom = new ConnectPoint(deviceId, PortNumber.portNumber(s));
274 ByteBuffer rawData = ByteBuffer.wrap(packetIn.data().asArray());
275 return new DefaultInboundPacket(receivedFrom, ethPkt, rawData);
276 } else {
277 throw new PiInterpreterException(format(
278 "Missing metadata '%s' in packet-in received from '%s': %s", INGRESS_PORT, deviceId, packetIn));
279 }
280 }
281
282 private PiPacketOperation createPiPacketOperation(ByteBuffer data, long portNumber) throws PiInterpreterException {
283 PiPacketMetadata metadata = createPacketMetadata(portNumber);
284 return PiPacketOperation.builder()
285 .withType(PACKET_OUT)
286 .withData(copyFrom(data))
287 .withMetadatas(ImmutableList.of(metadata))
288 .build();
289 }
290
291 private PiPacketMetadata createPacketMetadata(long portNumber) throws PiInterpreterException {
292 initTargetSpecificAttributes();
293 try {
294 return PiPacketMetadata.builder()
295 .withId(PiPacketMetadataId.of(EGRESS_PORT))
296 .withValue(fit(copyFrom(portNumber), portFieldBitWidth))
297 .build();
298 } catch (ImmutableByteSequence.ByteSequenceTrimException e) {
299 throw new PiInterpreterException(format("Port number %d too big, %s", portNumber, e.getMessage()));
300 }
301 }
302
303 /**
304 * Returns an action instance with no runtime parameters.
305 */
306 private PiAction actionWithName(String name) {
307 return PiAction.builder().withId(PiActionId.of(name)).build();
308 }
309
310 @Override
311 public Optional<PiHeaderFieldId> mapCriterionType(Criterion.Type type) {
312 initTargetSpecificAttributes();
313 return Optional.ofNullable(criterionMap.get(type));
314 }
315
316 @Override
317 public Optional<Criterion.Type> mapPiHeaderFieldId(PiHeaderFieldId headerFieldId) {
318 initTargetSpecificAttributes();
319 return Optional.ofNullable(criterionMap.inverse().get(headerFieldId));
320 }
321
322 @Override
323 public Optional<PiTableId> mapFlowRuleTableId(int flowRuleTableId) {
324 return Optional.ofNullable(TABLE_MAP.get(flowRuleTableId));
325 }
326
327 @Override
328 public Optional<Integer> mapPiTableId(PiTableId piTableId) {
329 return Optional.ofNullable(TABLE_MAP.inverse().get(piTableId));
330 }
331}