blob: d069e2a1899591994078ec6b4505590e5f41b66e [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;
21import org.onlab.packet.Ethernet;
22import org.onlab.util.ImmutableByteSequence;
23import org.onosproject.net.ConnectPoint;
24import org.onosproject.net.DeviceId;
25import org.onosproject.net.Port;
26import org.onosproject.net.PortNumber;
27import org.onosproject.net.device.DeviceService;
28import org.onosproject.net.driver.AbstractHandlerBehaviour;
29import org.onosproject.net.flow.TrafficTreatment;
30import org.onosproject.net.flow.criteria.Criterion;
31import org.onosproject.net.flow.instructions.Instruction;
32import org.onosproject.net.flow.instructions.Instructions;
Yi Tseng82512da2017-08-16 19:46:36 -070033import org.onosproject.net.flow.instructions.PiInstruction;
Carmelo Casconea62ac3d2017-08-30 03:19:00 +020034import org.onosproject.net.packet.DefaultInboundPacket;
35import org.onosproject.net.packet.InboundPacket;
36import org.onosproject.net.packet.OutboundPacket;
37import org.onosproject.net.pi.model.PiHeaderFieldModel;
38import org.onosproject.net.pi.model.PiPipeconf;
39import org.onosproject.net.pi.model.PiPipeconfId;
40import org.onosproject.net.pi.model.PiPipelineInterpreter;
41import org.onosproject.net.pi.model.PiPipelineModel;
42import org.onosproject.net.pi.model.PiTableModel;
43import org.onosproject.net.pi.runtime.PiAction;
44import org.onosproject.net.pi.runtime.PiActionId;
45import org.onosproject.net.pi.runtime.PiActionParam;
46import org.onosproject.net.pi.runtime.PiActionParamId;
Carmelo Cascone7f75be42017-09-07 14:37:02 +020047import org.onosproject.net.pi.runtime.PiCounterId;
48import org.onosproject.net.pi.runtime.PiCounterType;
Carmelo Casconea62ac3d2017-08-30 03:19:00 +020049import org.onosproject.net.pi.runtime.PiHeaderFieldId;
50import org.onosproject.net.pi.runtime.PiPacketMetadata;
51import org.onosproject.net.pi.runtime.PiPacketMetadataId;
52import org.onosproject.net.pi.runtime.PiPacketOperation;
53import org.onosproject.net.pi.runtime.PiPipeconfService;
54import org.onosproject.net.pi.runtime.PiTableId;
55
56import java.nio.ByteBuffer;
57import java.util.Collection;
58import java.util.List;
59import java.util.Optional;
60
61import static java.lang.String.format;
62import static java.util.stream.Collectors.toList;
63import static org.onlab.util.ImmutableByteSequence.copyFrom;
64import static org.onlab.util.ImmutableByteSequence.fit;
65import static org.onosproject.net.PortNumber.CONTROLLER;
66import static org.onosproject.net.PortNumber.FLOOD;
67import static org.onosproject.net.flow.instructions.Instruction.Type.OUTPUT;
68import static org.onosproject.net.pi.runtime.PiPacketOperation.Type.PACKET_OUT;
69
70/**
71 * Implementation of an interpreter that can be used for any P4 program based on default.p4 (i.e. those under
72 * onos/tools/test/p4src).
73 */
74public class DefaultP4Interpreter extends AbstractHandlerBehaviour implements PiPipelineInterpreter {
75
76 // FIXME: Should move this class out of the p4runtime drivers.
77 // e.g. in a dedicated onos/pipeconf directory, along with any related P4 source code.
78
79 public static final String TABLE0 = "table0";
Carmelo Cascone7f75be42017-09-07 14:37:02 +020080 public static final String TABLE0_COUNTER = "table0_counter";
Yi Tsenga87b40c2017-09-10 00:59:03 -070081 public static final String ECMP = "ecmp";
Carmelo Casconea62ac3d2017-08-30 03:19:00 +020082 public static final String SEND_TO_CPU = "send_to_cpu";
83 public static final String PORT = "port";
Carmelo Casconeeb018122017-09-06 13:16:03 +020084 public static final String DROP = "_drop";
Carmelo Casconea62ac3d2017-08-30 03:19:00 +020085 public static final String SET_EGRESS_PORT = "set_egress_port";
86 public static final String EGRESS_PORT = "egress_port";
87 public static final String INGRESS_PORT = "ingress_port";
88
Carmelo Cascone7f75be42017-09-07 14:37:02 +020089 private static final PiTableId TABLE0_ID = PiTableId.of(TABLE0);
Yi Tsenga87b40c2017-09-10 00:59:03 -070090 private static final PiTableId ECMP_ID = PiTableId.of(ECMP);
Carmelo Cascone7f75be42017-09-07 14:37:02 +020091
Carmelo Casconea62ac3d2017-08-30 03:19:00 +020092 protected static final PiHeaderFieldId ETH_DST_ID = PiHeaderFieldId.of("ethernet", "dstAddr");
93 protected static final PiHeaderFieldId ETH_SRC_ID = PiHeaderFieldId.of("ethernet", "srcAddr");
94 protected static final PiHeaderFieldId ETH_TYPE_ID = PiHeaderFieldId.of("ethernet", "etherType");
95
96 private static final ImmutableBiMap<Integer, PiTableId> TABLE_MAP = ImmutableBiMap.of(
Yi Tsenga87b40c2017-09-10 00:59:03 -070097 0, TABLE0_ID,
98 1, ECMP_ID);
Carmelo Cascone7f75be42017-09-07 14:37:02 +020099
100 private static final ImmutableBiMap<PiTableId, PiCounterId> TABLE_COUNTER_MAP = ImmutableBiMap.of(
101 TABLE0_ID, PiCounterId.of(TABLE0_COUNTER, PiCounterType.DIRECT));
Carmelo Casconea62ac3d2017-08-30 03:19:00 +0200102
103 private boolean targetAttributesInitialized = false;
104
105 /*
106 The following attributes are target-specific, i.e. they might change from one target to another.
107 */
108 private ImmutableBiMap<Criterion.Type, PiHeaderFieldId> criterionMap;
109 private int portFieldBitWidth;
110
111 /**
112 * Populates target-specific attributes based on this device's pipeline model.
113 */
114 private synchronized void initTargetSpecificAttributes() {
115 if (targetAttributesInitialized) {
116 return;
117 }
118
119 DeviceId deviceId = this.handler().data().deviceId();
120 PiPipeconfService pipeconfService = this.handler().get(PiPipeconfService.class);
121 PiPipeconfId pipeconfId = pipeconfService.ofDevice(deviceId)
122 .orElseThrow(() -> new RuntimeException(format(
123 "Unable to get current pipeconf for device %s", this.data().deviceId())));
124 PiPipeconf pipeconf = pipeconfService.getPipeconf(pipeconfId)
125 .orElseThrow(() -> new RuntimeException(format(
126 "Pipeconf %s is not registered", pipeconfId)));
127 PiPipelineModel model = pipeconf.pipelineModel();
128
129 this.portFieldBitWidth = extractPortFieldBitWidth(model);
130 this.criterionMap = new ImmutableBiMap.Builder<Criterion.Type, PiHeaderFieldId>()
131 .put(Criterion.Type.IN_PORT, extractInPortFieldId(model))
132 .put(Criterion.Type.ETH_DST, ETH_DST_ID)
133 .put(Criterion.Type.ETH_SRC, ETH_SRC_ID)
134 .put(Criterion.Type.ETH_TYPE, ETH_TYPE_ID)
135 .build();
136
137 this.targetAttributesInitialized = true;
138 }
139
140 private static PiHeaderFieldId extractInPortFieldId(PiPipelineModel model) {
141 /*
142 For the targets we currently support, the field name is "ingress_port", but we miss the header name, which is
143 target-specific. We know table0 defines that field as a match key, we look for it and we get the header name.
144 */
145 PiTableModel tableModel = model.table(TABLE0).orElseThrow(() -> new RuntimeException(format(
146 "No such table '%s' in pipeline model", TABLE0)));
147 PiHeaderFieldModel fieldModel = tableModel.matchFields().stream()
148 .filter(m -> m.field().type().name().equals(INGRESS_PORT))
149 .findFirst()
150 .orElseThrow(() -> new RuntimeException(format(
151 "No such match field in table '%s' with name '%s'", TABLE0, INGRESS_PORT)))
152 .field();
153 return PiHeaderFieldId.of(fieldModel.header().name(), INGRESS_PORT);
154 }
155
156 private static int extractPortFieldBitWidth(PiPipelineModel model) {
157 /*
158 Get it form the set_egress_port action parameters.
159 */
160 return model
161 .action(SET_EGRESS_PORT).orElseThrow(() -> new RuntimeException(format(
162 "No such action '%s' in pipeline model", SET_EGRESS_PORT)))
163 .param(PORT).orElseThrow(() -> new RuntimeException(format(
164 "No such parameter '%s' of action '%s' in pipeline model", PORT, SET_EGRESS_PORT)))
165 .bitWidth();
166 }
167
168
169 @Override
170 public PiAction mapTreatment(TrafficTreatment treatment, PiTableId piTableId) throws PiInterpreterException {
Yi Tseng82512da2017-08-16 19:46:36 -0700171 initTargetSpecificAttributes();
Carmelo Casconea62ac3d2017-08-30 03:19:00 +0200172 if (treatment.allInstructions().size() == 0) {
173 // No instructions means drop for us.
174 return actionWithName(DROP);
175 } else if (treatment.allInstructions().size() > 1) {
176 // Otherwise, we understand treatments with only 1 instruction.
177 throw new PiPipelineInterpreter.PiInterpreterException("Treatment has multiple instructions");
178 }
179
180 Instruction instruction = treatment.allInstructions().get(0);
181
182 switch (instruction.type()) {
183 case OUTPUT:
184 Instructions.OutputInstruction outInstruction = (Instructions.OutputInstruction) instruction;
Yi Tseng82512da2017-08-16 19:46:36 -0700185 return outputPiAction(outInstruction);
186 case PROTOCOL_INDEPENDENT:
187 PiInstruction piInstruction = (PiInstruction) instruction;
188 return (PiAction) piInstruction.action();
Carmelo Casconea62ac3d2017-08-30 03:19:00 +0200189 case NOACTION:
190 return actionWithName(DROP);
191 default:
192 throw new PiInterpreterException(format("Instruction type '%s' not supported", instruction.type()));
193 }
194 }
195
Yi Tseng82512da2017-08-16 19:46:36 -0700196 private PiAction outputPiAction(Instructions.OutputInstruction outInstruction) throws PiInterpreterException {
197 PortNumber port = outInstruction.port();
198 if (!port.isLogical()) {
199 try {
200 return PiAction.builder()
201 .withId(PiActionId.of(SET_EGRESS_PORT))
202 .withParameter(new PiActionParam(PiActionParamId.of(PORT),
203 fit(copyFrom(port.toLong()), portFieldBitWidth)))
204 .build();
205 } catch (ImmutableByteSequence.ByteSequenceTrimException e) {
206 throw new PiInterpreterException(e.getMessage());
207 }
208 } else if (port.equals(CONTROLLER)) {
209 return actionWithName(SEND_TO_CPU);
210 } else {
211 throw new PiInterpreterException(format("Egress on logical port '%s' not supported", port));
212 }
213 }
214
Carmelo Casconea62ac3d2017-08-30 03:19:00 +0200215 @Override
Carmelo Cascone7f75be42017-09-07 14:37:02 +0200216 public Optional<PiCounterId> mapTableCounter(PiTableId piTableId) {
217 return Optional.ofNullable(TABLE_COUNTER_MAP.get(piTableId));
218 }
219
220 @Override
Carmelo Casconea62ac3d2017-08-30 03:19:00 +0200221 public Collection<PiPacketOperation> mapOutboundPacket(OutboundPacket packet)
222 throws PiInterpreterException {
223 TrafficTreatment treatment = packet.treatment();
224
225 // default.p4 supports only OUTPUT instructions.
226 List<Instructions.OutputInstruction> outInstructions = treatment.allInstructions()
227 .stream()
228 .filter(i -> i.type().equals(OUTPUT))
229 .map(i -> (Instructions.OutputInstruction) i)
230 .collect(toList());
231
232 if (treatment.allInstructions().size() != outInstructions.size()) {
233 // There are other instructions that are not of type OUTPUT.
234 throw new PiInterpreterException("Treatment not supported: " + treatment);
235 }
236
237 ImmutableList.Builder<PiPacketOperation> builder = ImmutableList.builder();
238 for (Instructions.OutputInstruction outInst : outInstructions) {
239 if (outInst.port().isLogical() && !outInst.port().equals(FLOOD)) {
240 throw new PiInterpreterException(format("Output on logical port '%s' not supported", outInst.port()));
241 } else if (outInst.port().equals(FLOOD)) {
242 // Since default.p4 does not support flooding, we create a packet operation for each switch port.
243 for (Port port : handler().get(DeviceService.class).getPorts(packet.sendThrough())) {
244 builder.add(createPiPacketOperation(packet.data(), port.number().toLong()));
245 }
246 } else {
247 builder.add(createPiPacketOperation(packet.data(), outInst.port().toLong()));
248 }
249 }
250 return builder.build();
251 }
252
253 @Override
254 public InboundPacket mapInboundPacket(DeviceId deviceId, PiPacketOperation packetIn)
255 throws PiInterpreterException {
256 // Assuming that the packet is ethernet, which is fine since default.p4 can deparse only ethernet packets.
257 Ethernet ethPkt = new Ethernet();
258
259 ethPkt.deserialize(packetIn.data().asArray(), 0, packetIn.data().size());
260
261 // Returns the ingress port packet metadata.
262 Optional<PiPacketMetadata> packetMetadata = packetIn.metadatas()
263 .stream().filter(metadata -> metadata.id().name().equals(INGRESS_PORT))
264 .findFirst();
265
266 if (packetMetadata.isPresent()) {
267 ImmutableByteSequence portByteSequence = packetMetadata.get().value();
268 short s = portByteSequence.asReadOnlyBuffer().getShort();
269 ConnectPoint receivedFrom = new ConnectPoint(deviceId, PortNumber.portNumber(s));
270 ByteBuffer rawData = ByteBuffer.wrap(packetIn.data().asArray());
271 return new DefaultInboundPacket(receivedFrom, ethPkt, rawData);
272 } else {
273 throw new PiInterpreterException(format(
274 "Missing metadata '%s' in packet-in received from '%s': %s", INGRESS_PORT, deviceId, packetIn));
275 }
276 }
277
278 private PiPacketOperation createPiPacketOperation(ByteBuffer data, long portNumber) throws PiInterpreterException {
279 PiPacketMetadata metadata = createPacketMetadata(portNumber);
280 return PiPacketOperation.builder()
281 .withType(PACKET_OUT)
282 .withData(copyFrom(data))
283 .withMetadatas(ImmutableList.of(metadata))
284 .build();
285 }
286
287 private PiPacketMetadata createPacketMetadata(long portNumber) throws PiInterpreterException {
288 initTargetSpecificAttributes();
289 try {
290 return PiPacketMetadata.builder()
291 .withId(PiPacketMetadataId.of(EGRESS_PORT))
292 .withValue(fit(copyFrom(portNumber), portFieldBitWidth))
293 .build();
294 } catch (ImmutableByteSequence.ByteSequenceTrimException e) {
295 throw new PiInterpreterException(format("Port number %d too big, %s", portNumber, e.getMessage()));
296 }
297 }
298
299 /**
300 * Returns an action instance with no runtime parameters.
301 */
302 private PiAction actionWithName(String name) {
303 return PiAction.builder().withId(PiActionId.of(name)).build();
304 }
305
306 @Override
307 public Optional<PiHeaderFieldId> mapCriterionType(Criterion.Type type) {
308 initTargetSpecificAttributes();
309 return Optional.ofNullable(criterionMap.get(type));
310 }
311
312 @Override
313 public Optional<Criterion.Type> mapPiHeaderFieldId(PiHeaderFieldId headerFieldId) {
314 initTargetSpecificAttributes();
315 return Optional.ofNullable(criterionMap.inverse().get(headerFieldId));
316 }
317
318 @Override
319 public Optional<PiTableId> mapFlowRuleTableId(int flowRuleTableId) {
320 return Optional.ofNullable(TABLE_MAP.get(flowRuleTableId));
321 }
322
323 @Override
324 public Optional<Integer> mapPiTableId(PiTableId piTableId) {
325 return Optional.ofNullable(TABLE_MAP.inverse().get(piTableId));
326 }
327}