ofproto: New feature to notify controllers of flow table changes.
[openvswitch] / lib / ofp-util.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012 Nicira, Inc.
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
17 #include <config.h>
18 #include "ofp-print.h"
19 #include <errno.h>
20 #include <inttypes.h>
21 #include <sys/types.h>
22 #include <netinet/in.h>
23 #include <netinet/icmp6.h>
24 #include <stdlib.h>
25 #include "autopath.h"
26 #include "bundle.h"
27 #include "byte-order.h"
28 #include "classifier.h"
29 #include "dynamic-string.h"
30 #include "learn.h"
31 #include "meta-flow.h"
32 #include "multipath.h"
33 #include "netdev.h"
34 #include "nx-match.h"
35 #include "ofp-actions.h"
36 #include "ofp-errors.h"
37 #include "ofp-util.h"
38 #include "ofpbuf.h"
39 #include "packets.h"
40 #include "random.h"
41 #include "unaligned.h"
42 #include "type-props.h"
43 #include "vlog.h"
44
45 VLOG_DEFINE_THIS_MODULE(ofp_util);
46
47 /* Rate limit for OpenFlow message parse errors.  These always indicate a bug
48  * in the peer and so there's not much point in showing a lot of them. */
49 static struct vlog_rate_limit bad_ofmsg_rl = VLOG_RATE_LIMIT_INIT(1, 5);
50
51 /* Given the wildcard bit count in the least-significant 6 of 'wcbits', returns
52  * an IP netmask with a 1 in each bit that must match and a 0 in each bit that
53  * is wildcarded.
54  *
55  * The bits in 'wcbits' are in the format used in enum ofp_flow_wildcards: 0
56  * is exact match, 1 ignores the LSB, 2 ignores the 2 least-significant bits,
57  * ..., 32 and higher wildcard the entire field.  This is the *opposite* of the
58  * usual convention where e.g. /24 indicates that 8 bits (not 24 bits) are
59  * wildcarded. */
60 ovs_be32
61 ofputil_wcbits_to_netmask(int wcbits)
62 {
63     wcbits &= 0x3f;
64     return wcbits < 32 ? htonl(~((1u << wcbits) - 1)) : 0;
65 }
66
67 /* Given the IP netmask 'netmask', returns the number of bits of the IP address
68  * that it wildcards, that is, the number of 0-bits in 'netmask', a number
69  * between 0 and 32 inclusive.
70  *
71  * If 'netmask' is not a CIDR netmask (see ip_is_cidr()), the return value will
72  * still be in the valid range but isn't otherwise meaningful. */
73 int
74 ofputil_netmask_to_wcbits(ovs_be32 netmask)
75 {
76     return 32 - ip_count_cidr_bits(netmask);
77 }
78
79 /* A list of the FWW_* and OFPFW10_ bits that have the same value, meaning, and
80  * name. */
81 #define WC_INVARIANT_LIST \
82     WC_INVARIANT_BIT(IN_PORT) \
83     WC_INVARIANT_BIT(DL_TYPE) \
84     WC_INVARIANT_BIT(NW_PROTO)
85
86 /* Verify that all of the invariant bits (as defined on WC_INVARIANT_LIST)
87  * actually have the same names and values. */
88 #define WC_INVARIANT_BIT(NAME) BUILD_ASSERT_DECL(FWW_##NAME == OFPFW10_##NAME);
89     WC_INVARIANT_LIST
90 #undef WC_INVARIANT_BIT
91
92 /* WC_INVARIANTS is the invariant bits (as defined on WC_INVARIANT_LIST) all
93  * OR'd together. */
94 static const flow_wildcards_t WC_INVARIANTS = 0
95 #define WC_INVARIANT_BIT(NAME) | FWW_##NAME
96     WC_INVARIANT_LIST
97 #undef WC_INVARIANT_BIT
98 ;
99
100 /* Converts the OpenFlow 1.0 wildcards in 'ofpfw' (OFPFW10_*) into a
101  * flow_wildcards in 'wc' for use in struct cls_rule.  It is the caller's
102  * responsibility to handle the special case where the flow match's dl_vlan is
103  * set to OFP_VLAN_NONE. */
104 void
105 ofputil_wildcard_from_ofpfw10(uint32_t ofpfw, struct flow_wildcards *wc)
106 {
107     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 12);
108
109     /* Initialize most of rule->wc. */
110     flow_wildcards_init_catchall(wc);
111     wc->wildcards = (OVS_FORCE flow_wildcards_t) ofpfw & WC_INVARIANTS;
112
113     /* Wildcard fields that aren't defined by ofp10_match or tun_id. */
114     wc->wildcards |= (FWW_ARP_SHA | FWW_ARP_THA | FWW_NW_ECN | FWW_NW_TTL
115                       | FWW_IPV6_LABEL);
116
117     if (ofpfw & OFPFW10_NW_TOS) {
118         /* OpenFlow 1.0 defines a TOS wildcard, but it's much later in
119          * the enum than we can use. */
120         wc->wildcards |= FWW_NW_DSCP;
121     }
122
123     wc->nw_src_mask = ofputil_wcbits_to_netmask(ofpfw >> OFPFW10_NW_SRC_SHIFT);
124     wc->nw_dst_mask = ofputil_wcbits_to_netmask(ofpfw >> OFPFW10_NW_DST_SHIFT);
125
126     if (!(ofpfw & OFPFW10_TP_SRC)) {
127         wc->tp_src_mask = htons(UINT16_MAX);
128     }
129     if (!(ofpfw & OFPFW10_TP_DST)) {
130         wc->tp_dst_mask = htons(UINT16_MAX);
131     }
132
133     if (!(ofpfw & OFPFW10_DL_SRC)) {
134         memset(wc->dl_src_mask, 0xff, ETH_ADDR_LEN);
135     }
136     if (!(ofpfw & OFPFW10_DL_DST)) {
137         memset(wc->dl_dst_mask, 0xff, ETH_ADDR_LEN);
138     }
139
140     /* VLAN TCI mask. */
141     if (!(ofpfw & OFPFW10_DL_VLAN_PCP)) {
142         wc->vlan_tci_mask |= htons(VLAN_PCP_MASK | VLAN_CFI);
143     }
144     if (!(ofpfw & OFPFW10_DL_VLAN)) {
145         wc->vlan_tci_mask |= htons(VLAN_VID_MASK | VLAN_CFI);
146     }
147 }
148
149 /* Converts the ofp10_match in 'match' into a cls_rule in 'rule', with the
150  * given 'priority'. */
151 void
152 ofputil_cls_rule_from_ofp10_match(const struct ofp10_match *match,
153                                   unsigned int priority, struct cls_rule *rule)
154 {
155     uint32_t ofpfw = ntohl(match->wildcards) & OFPFW10_ALL;
156
157     /* Initialize rule->priority, rule->wc. */
158     rule->priority = !ofpfw ? UINT16_MAX : priority;
159     ofputil_wildcard_from_ofpfw10(ofpfw, &rule->wc);
160
161     /* Initialize most of rule->flow. */
162     rule->flow.nw_src = match->nw_src;
163     rule->flow.nw_dst = match->nw_dst;
164     rule->flow.in_port = ntohs(match->in_port);
165     rule->flow.dl_type = ofputil_dl_type_from_openflow(match->dl_type);
166     rule->flow.tp_src = match->tp_src;
167     rule->flow.tp_dst = match->tp_dst;
168     memcpy(rule->flow.dl_src, match->dl_src, ETH_ADDR_LEN);
169     memcpy(rule->flow.dl_dst, match->dl_dst, ETH_ADDR_LEN);
170     rule->flow.nw_tos = match->nw_tos & IP_DSCP_MASK;
171     rule->flow.nw_proto = match->nw_proto;
172
173     /* Translate VLANs. */
174     if (!(ofpfw & OFPFW10_DL_VLAN) &&
175         match->dl_vlan == htons(OFP10_VLAN_NONE)) {
176         /* Match only packets without 802.1Q header.
177          *
178          * When OFPFW10_DL_VLAN_PCP is wildcarded, this is obviously correct.
179          *
180          * If OFPFW10_DL_VLAN_PCP is matched, the flow match is contradictory,
181          * because we can't have a specific PCP without an 802.1Q header.
182          * However, older versions of OVS treated this as matching packets
183          * withut an 802.1Q header, so we do here too. */
184         rule->flow.vlan_tci = htons(0);
185         rule->wc.vlan_tci_mask = htons(0xffff);
186     } else {
187         ovs_be16 vid, pcp, tci;
188
189         vid = match->dl_vlan & htons(VLAN_VID_MASK);
190         pcp = htons((match->dl_vlan_pcp << VLAN_PCP_SHIFT) & VLAN_PCP_MASK);
191         tci = vid | pcp | htons(VLAN_CFI);
192         rule->flow.vlan_tci = tci & rule->wc.vlan_tci_mask;
193     }
194
195     /* Clean up. */
196     cls_rule_zero_wildcarded_fields(rule);
197 }
198
199 /* Convert 'rule' into the OpenFlow 1.0 match structure 'match'. */
200 void
201 ofputil_cls_rule_to_ofp10_match(const struct cls_rule *rule,
202                                 struct ofp10_match *match)
203 {
204     const struct flow_wildcards *wc = &rule->wc;
205     uint32_t ofpfw;
206
207     /* Figure out most OpenFlow wildcards. */
208     ofpfw = (OVS_FORCE uint32_t) (wc->wildcards & WC_INVARIANTS);
209     ofpfw |= (ofputil_netmask_to_wcbits(wc->nw_src_mask)
210               << OFPFW10_NW_SRC_SHIFT);
211     ofpfw |= (ofputil_netmask_to_wcbits(wc->nw_dst_mask)
212               << OFPFW10_NW_DST_SHIFT);
213     if (wc->wildcards & FWW_NW_DSCP) {
214         ofpfw |= OFPFW10_NW_TOS;
215     }
216     if (!wc->tp_src_mask) {
217         ofpfw |= OFPFW10_TP_SRC;
218     }
219     if (!wc->tp_dst_mask) {
220         ofpfw |= OFPFW10_TP_DST;
221     }
222     if (eth_addr_is_zero(wc->dl_src_mask)) {
223         ofpfw |= OFPFW10_DL_SRC;
224     }
225     if (eth_addr_is_zero(wc->dl_dst_mask)) {
226         ofpfw |= OFPFW10_DL_DST;
227     }
228
229     /* Translate VLANs. */
230     match->dl_vlan = htons(0);
231     match->dl_vlan_pcp = 0;
232     if (rule->wc.vlan_tci_mask == htons(0)) {
233         ofpfw |= OFPFW10_DL_VLAN | OFPFW10_DL_VLAN_PCP;
234     } else if (rule->wc.vlan_tci_mask & htons(VLAN_CFI)
235                && !(rule->flow.vlan_tci & htons(VLAN_CFI))) {
236         match->dl_vlan = htons(OFP10_VLAN_NONE);
237     } else {
238         if (!(rule->wc.vlan_tci_mask & htons(VLAN_VID_MASK))) {
239             ofpfw |= OFPFW10_DL_VLAN;
240         } else {
241             match->dl_vlan = htons(vlan_tci_to_vid(rule->flow.vlan_tci));
242         }
243
244         if (!(rule->wc.vlan_tci_mask & htons(VLAN_PCP_MASK))) {
245             ofpfw |= OFPFW10_DL_VLAN_PCP;
246         } else {
247             match->dl_vlan_pcp = vlan_tci_to_pcp(rule->flow.vlan_tci);
248         }
249     }
250
251     /* Compose most of the match structure. */
252     match->wildcards = htonl(ofpfw);
253     match->in_port = htons(rule->flow.in_port);
254     memcpy(match->dl_src, rule->flow.dl_src, ETH_ADDR_LEN);
255     memcpy(match->dl_dst, rule->flow.dl_dst, ETH_ADDR_LEN);
256     match->dl_type = ofputil_dl_type_to_openflow(rule->flow.dl_type);
257     match->nw_src = rule->flow.nw_src;
258     match->nw_dst = rule->flow.nw_dst;
259     match->nw_tos = rule->flow.nw_tos & IP_DSCP_MASK;
260     match->nw_proto = rule->flow.nw_proto;
261     match->tp_src = rule->flow.tp_src;
262     match->tp_dst = rule->flow.tp_dst;
263     memset(match->pad1, '\0', sizeof match->pad1);
264     memset(match->pad2, '\0', sizeof match->pad2);
265 }
266
267 /* Converts the ofp11_match in 'match' into a cls_rule in 'rule', with the
268  * given 'priority'.  Returns 0 if successful, otherwise an OFPERR_* value. */
269 enum ofperr
270 ofputil_cls_rule_from_ofp11_match(const struct ofp11_match *match,
271                                   unsigned int priority,
272                                   struct cls_rule *rule)
273 {
274     uint16_t wc = ntohl(match->wildcards);
275     uint8_t dl_src_mask[ETH_ADDR_LEN];
276     uint8_t dl_dst_mask[ETH_ADDR_LEN];
277     bool ipv4, arp;
278     int i;
279
280     cls_rule_init_catchall(rule, priority);
281
282     if (!(wc & OFPFW11_IN_PORT)) {
283         uint16_t ofp_port;
284         enum ofperr error;
285
286         error = ofputil_port_from_ofp11(match->in_port, &ofp_port);
287         if (error) {
288             return OFPERR_OFPBMC_BAD_VALUE;
289         }
290         cls_rule_set_in_port(rule, ofp_port);
291     }
292
293     for (i = 0; i < ETH_ADDR_LEN; i++) {
294         dl_src_mask[i] = ~match->dl_src_mask[i];
295     }
296     cls_rule_set_dl_src_masked(rule, match->dl_src, dl_src_mask);
297
298     for (i = 0; i < ETH_ADDR_LEN; i++) {
299         dl_dst_mask[i] = ~match->dl_dst_mask[i];
300     }
301     cls_rule_set_dl_dst_masked(rule, match->dl_dst, dl_dst_mask);
302
303     if (!(wc & OFPFW11_DL_VLAN)) {
304         if (match->dl_vlan == htons(OFPVID11_NONE)) {
305             /* Match only packets without a VLAN tag. */
306             rule->flow.vlan_tci = htons(0);
307             rule->wc.vlan_tci_mask = htons(UINT16_MAX);
308         } else {
309             if (match->dl_vlan == htons(OFPVID11_ANY)) {
310                 /* Match any packet with a VLAN tag regardless of VID. */
311                 rule->flow.vlan_tci = htons(VLAN_CFI);
312                 rule->wc.vlan_tci_mask = htons(VLAN_CFI);
313             } else if (ntohs(match->dl_vlan) < 4096) {
314                 /* Match only packets with the specified VLAN VID. */
315                 rule->flow.vlan_tci = htons(VLAN_CFI) | match->dl_vlan;
316                 rule->wc.vlan_tci_mask = htons(VLAN_CFI | VLAN_VID_MASK);
317             } else {
318                 /* Invalid VID. */
319                 return OFPERR_OFPBMC_BAD_VALUE;
320             }
321
322             if (!(wc & OFPFW11_DL_VLAN_PCP)) {
323                 if (match->dl_vlan_pcp <= 7) {
324                     rule->flow.vlan_tci |= htons(match->dl_vlan_pcp
325                                                  << VLAN_PCP_SHIFT);
326                     rule->wc.vlan_tci_mask |= htons(VLAN_PCP_MASK);
327                 } else {
328                     /* Invalid PCP. */
329                     return OFPERR_OFPBMC_BAD_VALUE;
330                 }
331             }
332         }
333     }
334
335     if (!(wc & OFPFW11_DL_TYPE)) {
336         cls_rule_set_dl_type(rule,
337                              ofputil_dl_type_from_openflow(match->dl_type));
338     }
339
340     ipv4 = rule->flow.dl_type == htons(ETH_TYPE_IP);
341     arp = rule->flow.dl_type == htons(ETH_TYPE_ARP);
342
343     if (ipv4 && !(wc & OFPFW11_NW_TOS)) {
344         if (match->nw_tos & ~IP_DSCP_MASK) {
345             /* Invalid TOS. */
346             return OFPERR_OFPBMC_BAD_VALUE;
347         }
348
349         cls_rule_set_nw_dscp(rule, match->nw_tos);
350     }
351
352     if (ipv4 || arp) {
353         if (!(wc & OFPFW11_NW_PROTO)) {
354             cls_rule_set_nw_proto(rule, match->nw_proto);
355         }
356         cls_rule_set_nw_src_masked(rule, match->nw_src, ~match->nw_src_mask);
357         cls_rule_set_nw_dst_masked(rule, match->nw_dst, ~match->nw_dst_mask);
358     }
359
360 #define OFPFW11_TP_ALL (OFPFW11_TP_SRC | OFPFW11_TP_DST)
361     if (ipv4 && (wc & OFPFW11_TP_ALL) != OFPFW11_TP_ALL) {
362         switch (rule->flow.nw_proto) {
363         case IPPROTO_ICMP:
364             /* "A.2.3 Flow Match Structures" in OF1.1 says:
365              *
366              *    The tp_src and tp_dst fields will be ignored unless the
367              *    network protocol specified is as TCP, UDP or SCTP.
368              *
369              * but I'm pretty sure we should support ICMP too, otherwise
370              * that's a regression from OF1.0. */
371             if (!(wc & OFPFW11_TP_SRC)) {
372                 uint16_t icmp_type = ntohs(match->tp_src);
373                 if (icmp_type < 0x100) {
374                     cls_rule_set_icmp_type(rule, icmp_type);
375                 } else {
376                     return OFPERR_OFPBMC_BAD_FIELD;
377                 }
378             }
379             if (!(wc & OFPFW11_TP_DST)) {
380                 uint16_t icmp_code = ntohs(match->tp_dst);
381                 if (icmp_code < 0x100) {
382                     cls_rule_set_icmp_code(rule, icmp_code);
383                 } else {
384                     return OFPERR_OFPBMC_BAD_FIELD;
385                 }
386             }
387             break;
388
389         case IPPROTO_TCP:
390         case IPPROTO_UDP:
391             if (!(wc & (OFPFW11_TP_SRC))) {
392                 cls_rule_set_tp_src(rule, match->tp_src);
393             }
394             if (!(wc & (OFPFW11_TP_DST))) {
395                 cls_rule_set_tp_dst(rule, match->tp_dst);
396             }
397             break;
398
399         case IPPROTO_SCTP:
400             /* We don't support SCTP and it seems that we should tell the
401              * controller, since OF1.1 implementations are supposed to. */
402             return OFPERR_OFPBMC_BAD_FIELD;
403
404         default:
405             /* OF1.1 says explicitly to ignore this. */
406             break;
407         }
408     }
409
410     if (rule->flow.dl_type == htons(ETH_TYPE_MPLS) ||
411         rule->flow.dl_type == htons(ETH_TYPE_MPLS_MCAST)) {
412         enum { OFPFW11_MPLS_ALL = OFPFW11_MPLS_LABEL | OFPFW11_MPLS_TC };
413
414         if ((wc & OFPFW11_MPLS_ALL) != OFPFW11_MPLS_ALL) {
415             /* MPLS not supported. */
416             return OFPERR_OFPBMC_BAD_TAG;
417         }
418     }
419
420     if (match->metadata_mask != htonll(UINT64_MAX)) {
421         cls_rule_set_metadata_masked(rule, match->metadata,
422                                      ~match->metadata_mask);
423     }
424
425     return 0;
426 }
427
428 /* Convert 'rule' into the OpenFlow 1.1 match structure 'match'. */
429 void
430 ofputil_cls_rule_to_ofp11_match(const struct cls_rule *rule,
431                                 struct ofp11_match *match)
432 {
433     uint32_t wc = 0;
434     int i;
435
436     memset(match, 0, sizeof *match);
437     match->omh.type = htons(OFPMT_STANDARD);
438     match->omh.length = htons(OFPMT11_STANDARD_LENGTH);
439
440     if (rule->wc.wildcards & FWW_IN_PORT) {
441         wc |= OFPFW11_IN_PORT;
442     } else {
443         match->in_port = ofputil_port_to_ofp11(rule->flow.in_port);
444     }
445
446
447     memcpy(match->dl_src, rule->flow.dl_src, ETH_ADDR_LEN);
448     for (i = 0; i < ETH_ADDR_LEN; i++) {
449         match->dl_src_mask[i] = ~rule->wc.dl_src_mask[i];
450     }
451
452     memcpy(match->dl_dst, rule->flow.dl_dst, ETH_ADDR_LEN);
453     for (i = 0; i < ETH_ADDR_LEN; i++) {
454         match->dl_dst_mask[i] = ~rule->wc.dl_dst_mask[i];
455     }
456
457     if (rule->wc.vlan_tci_mask == htons(0)) {
458         wc |= OFPFW11_DL_VLAN | OFPFW11_DL_VLAN_PCP;
459     } else if (rule->wc.vlan_tci_mask & htons(VLAN_CFI)
460                && !(rule->flow.vlan_tci & htons(VLAN_CFI))) {
461         match->dl_vlan = htons(OFPVID11_NONE);
462         wc |= OFPFW11_DL_VLAN_PCP;
463     } else {
464         if (!(rule->wc.vlan_tci_mask & htons(VLAN_VID_MASK))) {
465             match->dl_vlan = htons(OFPVID11_ANY);
466         } else {
467             match->dl_vlan = htons(vlan_tci_to_vid(rule->flow.vlan_tci));
468         }
469
470         if (!(rule->wc.vlan_tci_mask & htons(VLAN_PCP_MASK))) {
471             wc |= OFPFW11_DL_VLAN_PCP;
472         } else {
473             match->dl_vlan_pcp = vlan_tci_to_pcp(rule->flow.vlan_tci);
474         }
475     }
476
477     if (rule->wc.wildcards & FWW_DL_TYPE) {
478         wc |= OFPFW11_DL_TYPE;
479     } else {
480         match->dl_type = ofputil_dl_type_to_openflow(rule->flow.dl_type);
481     }
482
483     if (rule->wc.wildcards & FWW_NW_DSCP) {
484         wc |= OFPFW11_NW_TOS;
485     } else {
486         match->nw_tos = rule->flow.nw_tos & IP_DSCP_MASK;
487     }
488
489     if (rule->wc.wildcards & FWW_NW_PROTO) {
490         wc |= OFPFW11_NW_PROTO;
491     } else {
492         match->nw_proto = rule->flow.nw_proto;
493     }
494
495     match->nw_src = rule->flow.nw_src;
496     match->nw_src_mask = ~rule->wc.nw_src_mask;
497     match->nw_dst = rule->flow.nw_dst;
498     match->nw_dst_mask = ~rule->wc.nw_dst_mask;
499
500     if (!rule->wc.tp_src_mask) {
501         wc |= OFPFW11_TP_SRC;
502     } else {
503         match->tp_src = rule->flow.tp_src;
504     }
505
506     if (!rule->wc.tp_dst_mask) {
507         wc |= OFPFW11_TP_DST;
508     } else {
509         match->tp_dst = rule->flow.tp_dst;
510     }
511
512     /* MPLS not supported. */
513     wc |= OFPFW11_MPLS_LABEL;
514     wc |= OFPFW11_MPLS_TC;
515
516     match->metadata = rule->flow.metadata;
517     match->metadata_mask = ~rule->wc.metadata_mask;
518
519     match->wildcards = htonl(wc);
520 }
521
522 /* Given a 'dl_type' value in the format used in struct flow, returns the
523  * corresponding 'dl_type' value for use in an ofp10_match or ofp11_match
524  * structure. */
525 ovs_be16
526 ofputil_dl_type_to_openflow(ovs_be16 flow_dl_type)
527 {
528     return (flow_dl_type == htons(FLOW_DL_TYPE_NONE)
529             ? htons(OFP_DL_TYPE_NOT_ETH_TYPE)
530             : flow_dl_type);
531 }
532
533 /* Given a 'dl_type' value in the format used in an ofp10_match or ofp11_match
534  * structure, returns the corresponding 'dl_type' value for use in struct
535  * flow. */
536 ovs_be16
537 ofputil_dl_type_from_openflow(ovs_be16 ofp_dl_type)
538 {
539     return (ofp_dl_type == htons(OFP_DL_TYPE_NOT_ETH_TYPE)
540             ? htons(FLOW_DL_TYPE_NONE)
541             : ofp_dl_type);
542 }
543
544 /* Returns a transaction ID to use for an outgoing OpenFlow message. */
545 static ovs_be32
546 alloc_xid(void)
547 {
548     static uint32_t next_xid = 1;
549     return htonl(next_xid++);
550 }
551 \f
552 /* Basic parsing of OpenFlow messages. */
553
554 struct ofputil_msg_type {
555     enum ofputil_msg_code code; /* OFPUTIL_*. */
556     uint8_t ofp_version;        /* An OpenFlow version or 0 for "any". */
557     uint32_t value;             /* OFPT_*, OFPST_*, NXT_*, or NXST_*. */
558     const char *name;           /* e.g. "OFPT_FLOW_REMOVED". */
559     unsigned int min_size;      /* Minimum total message size in bytes. */
560     /* 0 if 'min_size' is the exact size that the message must be.  Otherwise,
561      * the message may exceed 'min_size' by an even multiple of this value. */
562     unsigned int extra_multiple;
563 };
564
565 /* Represents a malformed OpenFlow message. */
566 static const struct ofputil_msg_type ofputil_invalid_type = {
567     OFPUTIL_MSG_INVALID, 0, 0, "OFPUTIL_MSG_INVALID", 0, 0
568 };
569
570 struct ofputil_msg_category {
571     const char *name;           /* e.g. "OpenFlow message" */
572     const struct ofputil_msg_type *types;
573     size_t n_types;
574     enum ofperr missing_error;  /* Error value for missing type. */
575 };
576
577 static enum ofperr
578 ofputil_check_length(const struct ofputil_msg_type *type, unsigned int size)
579 {
580     switch (type->extra_multiple) {
581     case 0:
582         if (size != type->min_size) {
583             VLOG_WARN_RL(&bad_ofmsg_rl, "received %s with incorrect "
584                          "length %u (expected length %u)",
585                          type->name, size, type->min_size);
586             return OFPERR_OFPBRC_BAD_LEN;
587         }
588         return 0;
589
590     case 1:
591         if (size < type->min_size) {
592             VLOG_WARN_RL(&bad_ofmsg_rl, "received %s with incorrect "
593                          "length %u (expected length at least %u bytes)",
594                          type->name, size, type->min_size);
595             return OFPERR_OFPBRC_BAD_LEN;
596         }
597         return 0;
598
599     default:
600         if (size < type->min_size
601             || (size - type->min_size) % type->extra_multiple) {
602             VLOG_WARN_RL(&bad_ofmsg_rl, "received %s with incorrect "
603                          "length %u (must be exactly %u bytes or longer "
604                          "by an integer multiple of %u bytes)",
605                          type->name, size,
606                          type->min_size, type->extra_multiple);
607             return OFPERR_OFPBRC_BAD_LEN;
608         }
609         return 0;
610     }
611 }
612
613 static enum ofperr
614 ofputil_lookup_openflow_message(const struct ofputil_msg_category *cat,
615                                 uint8_t version, uint32_t value,
616                                 const struct ofputil_msg_type **typep)
617 {
618     const struct ofputil_msg_type *type;
619
620     for (type = cat->types; type < &cat->types[cat->n_types]; type++) {
621         if (type->value == value
622             && (!type->ofp_version || version == type->ofp_version)) {
623             *typep = type;
624             return 0;
625         }
626     }
627
628     VLOG_WARN_RL(&bad_ofmsg_rl, "received %s of unknown type %"PRIu32,
629                  cat->name, value);
630     return cat->missing_error;
631 }
632
633 static enum ofperr
634 ofputil_decode_vendor(const struct ofp_header *oh, size_t length,
635                       const struct ofputil_msg_type **typep)
636 {
637     static const struct ofputil_msg_type nxt_messages[] = {
638         { OFPUTIL_NXT_ROLE_REQUEST, OFP10_VERSION,
639           NXT_ROLE_REQUEST, "NXT_ROLE_REQUEST",
640           sizeof(struct nx_role_request), 0 },
641
642         { OFPUTIL_NXT_ROLE_REPLY, OFP10_VERSION,
643           NXT_ROLE_REPLY, "NXT_ROLE_REPLY",
644           sizeof(struct nx_role_request), 0 },
645
646         { OFPUTIL_NXT_SET_FLOW_FORMAT, OFP10_VERSION,
647           NXT_SET_FLOW_FORMAT, "NXT_SET_FLOW_FORMAT",
648           sizeof(struct nx_set_flow_format), 0 },
649
650         { OFPUTIL_NXT_SET_PACKET_IN_FORMAT, OFP10_VERSION,
651           NXT_SET_PACKET_IN_FORMAT, "NXT_SET_PACKET_IN_FORMAT",
652           sizeof(struct nx_set_packet_in_format), 0 },
653
654         { OFPUTIL_NXT_PACKET_IN, OFP10_VERSION,
655           NXT_PACKET_IN, "NXT_PACKET_IN",
656           sizeof(struct nx_packet_in), 1 },
657
658         { OFPUTIL_NXT_FLOW_MOD, OFP10_VERSION,
659           NXT_FLOW_MOD, "NXT_FLOW_MOD",
660           sizeof(struct nx_flow_mod), 8 },
661
662         { OFPUTIL_NXT_FLOW_REMOVED, OFP10_VERSION,
663           NXT_FLOW_REMOVED, "NXT_FLOW_REMOVED",
664           sizeof(struct nx_flow_removed), 8 },
665
666         { OFPUTIL_NXT_FLOW_MOD_TABLE_ID, OFP10_VERSION,
667           NXT_FLOW_MOD_TABLE_ID, "NXT_FLOW_MOD_TABLE_ID",
668           sizeof(struct nx_flow_mod_table_id), 0 },
669
670         { OFPUTIL_NXT_FLOW_AGE, OFP10_VERSION,
671           NXT_FLOW_AGE, "NXT_FLOW_AGE",
672           sizeof(struct nicira_header), 0 },
673
674         { OFPUTIL_NXT_SET_ASYNC_CONFIG, OFP10_VERSION,
675           NXT_SET_ASYNC_CONFIG, "NXT_SET_ASYNC_CONFIG",
676           sizeof(struct nx_async_config), 0 },
677
678         { OFPUTIL_NXT_SET_CONTROLLER_ID, OFP10_VERSION,
679           NXT_SET_CONTROLLER_ID, "NXT_SET_CONTROLLER_ID",
680           sizeof(struct nx_controller_id), 0 },
681
682         { OFPUTIL_NXT_FLOW_MONITOR_CANCEL, OFP10_VERSION,
683           NXT_FLOW_MONITOR_CANCEL, "NXT_FLOW_MONITOR_CANCEL",
684           sizeof(struct nx_flow_monitor_cancel), 0 },
685
686         { OFPUTIL_NXT_FLOW_MONITOR_PAUSED, OFP10_VERSION,
687           NXT_FLOW_MONITOR_PAUSED, "NXT_FLOW_MONITOR_PAUSED",
688           sizeof(struct nicira_header), 0 },
689
690         { OFPUTIL_NXT_FLOW_MONITOR_RESUMED, OFP10_VERSION,
691           NXT_FLOW_MONITOR_RESUMED, "NXT_FLOW_MONITOR_RESUMED",
692           sizeof(struct nicira_header), 0 },
693     };
694
695     static const struct ofputil_msg_category nxt_category = {
696         "Nicira extension message",
697         nxt_messages, ARRAY_SIZE(nxt_messages),
698         OFPERR_OFPBRC_BAD_SUBTYPE
699     };
700
701     const struct ofp_vendor_header *ovh;
702     const struct nicira_header *nh;
703
704     if (length < sizeof(struct ofp_vendor_header)) {
705         if (length == ntohs(oh->length)) {
706             VLOG_WARN_RL(&bad_ofmsg_rl, "truncated vendor message");
707         }
708         return OFPERR_OFPBRC_BAD_LEN;
709     }
710
711     ovh = (const struct ofp_vendor_header *) oh;
712     if (ovh->vendor != htonl(NX_VENDOR_ID)) {
713         VLOG_WARN_RL(&bad_ofmsg_rl, "received vendor message for unknown "
714                      "vendor %"PRIx32, ntohl(ovh->vendor));
715         return OFPERR_OFPBRC_BAD_VENDOR;
716     }
717
718     if (length < sizeof(struct nicira_header)) {
719         if (length == ntohs(oh->length)) {
720             VLOG_WARN_RL(&bad_ofmsg_rl, "received Nicira vendor message of "
721                          "length %u (expected at least %zu)",
722                          ntohs(ovh->header.length),
723                          sizeof(struct nicira_header));
724         }
725         return OFPERR_OFPBRC_BAD_LEN;
726     }
727
728     nh = (const struct nicira_header *) oh;
729     return ofputil_lookup_openflow_message(&nxt_category, oh->version,
730                                            ntohl(nh->subtype), typep);
731 }
732
733 static enum ofperr
734 check_nxstats_msg(const struct ofp_header *oh, size_t length)
735 {
736     const struct ofp_stats_msg *osm = (const struct ofp_stats_msg *) oh;
737     ovs_be32 vendor;
738
739     if (length < sizeof(struct ofp_vendor_stats_msg)) {
740         if (length == ntohs(oh->length)) {
741             VLOG_WARN_RL(&bad_ofmsg_rl, "truncated vendor stats message");
742         }
743         return OFPERR_OFPBRC_BAD_LEN;
744     }
745
746     memcpy(&vendor, osm + 1, sizeof vendor);
747     if (vendor != htonl(NX_VENDOR_ID)) {
748         VLOG_WARN_RL(&bad_ofmsg_rl, "received vendor stats message for "
749                      "unknown vendor %"PRIx32, ntohl(vendor));
750         return OFPERR_OFPBRC_BAD_VENDOR;
751     }
752
753     if (length < sizeof(struct nicira_stats_msg)) {
754         if (length == ntohs(osm->header.length)) {
755             VLOG_WARN_RL(&bad_ofmsg_rl, "truncated Nicira stats message");
756         }
757         return OFPERR_OFPBRC_BAD_LEN;
758     }
759
760     return 0;
761 }
762
763 static enum ofperr
764 ofputil_decode_nxst_request(const struct ofp_header *oh, size_t length,
765                             const struct ofputil_msg_type **typep)
766 {
767     static const struct ofputil_msg_type nxst_requests[] = {
768         { OFPUTIL_NXST_FLOW_REQUEST, OFP10_VERSION,
769           NXST_FLOW, "NXST_FLOW request",
770           sizeof(struct nx_flow_stats_request), 8 },
771
772         { OFPUTIL_NXST_AGGREGATE_REQUEST, OFP10_VERSION,
773           NXST_AGGREGATE, "NXST_AGGREGATE request",
774           sizeof(struct nx_aggregate_stats_request), 8 },
775
776         { OFPUTIL_NXST_FLOW_MONITOR_REQUEST, OFP10_VERSION,
777           NXST_FLOW_MONITOR, "NXST_FLOW_MONITOR request",
778           sizeof(struct nicira_stats_msg), 8 },
779     };
780
781     static const struct ofputil_msg_category nxst_request_category = {
782         "Nicira extension statistics request",
783         nxst_requests, ARRAY_SIZE(nxst_requests),
784         OFPERR_OFPBRC_BAD_SUBTYPE
785     };
786
787     const struct nicira_stats_msg *nsm;
788     enum ofperr error;
789
790     error = check_nxstats_msg(oh, length);
791     if (error) {
792         return error;
793     }
794
795     nsm = (struct nicira_stats_msg *) oh;
796     return ofputil_lookup_openflow_message(&nxst_request_category, oh->version,
797                                            ntohl(nsm->subtype), typep);
798 }
799
800 static enum ofperr
801 ofputil_decode_nxst_reply(const struct ofp_header *oh, size_t length,
802                           const struct ofputil_msg_type **typep)
803 {
804     static const struct ofputil_msg_type nxst_replies[] = {
805         { OFPUTIL_NXST_FLOW_REPLY, OFP10_VERSION,
806           NXST_FLOW, "NXST_FLOW reply",
807           sizeof(struct nicira_stats_msg), 8 },
808
809         { OFPUTIL_NXST_AGGREGATE_REPLY, OFP10_VERSION,
810           NXST_AGGREGATE, "NXST_AGGREGATE reply",
811           sizeof(struct nx_aggregate_stats_reply), 0 },
812
813         { OFPUTIL_NXST_FLOW_MONITOR_REPLY, OFP10_VERSION,
814           NXST_FLOW_MONITOR, "NXST_FLOW_MONITOR reply",
815           sizeof(struct nicira_stats_msg), 8 },
816     };
817
818     static const struct ofputil_msg_category nxst_reply_category = {
819         "Nicira extension statistics reply",
820         nxst_replies, ARRAY_SIZE(nxst_replies),
821         OFPERR_OFPBRC_BAD_SUBTYPE
822     };
823
824     const struct nicira_stats_msg *nsm;
825     enum ofperr error;
826
827     error = check_nxstats_msg(oh, length);
828     if (error) {
829         return error;
830     }
831
832     nsm = (struct nicira_stats_msg *) oh;
833     return ofputil_lookup_openflow_message(&nxst_reply_category, oh->version,
834                                            ntohl(nsm->subtype), typep);
835 }
836
837 static enum ofperr
838 check_stats_msg(const struct ofp_header *oh, size_t length)
839 {
840     if (length < sizeof(struct ofp_stats_msg)) {
841         if (length == ntohs(oh->length)) {
842             VLOG_WARN_RL(&bad_ofmsg_rl, "truncated stats message");
843         }
844         return OFPERR_OFPBRC_BAD_LEN;
845     }
846
847     return 0;
848 }
849
850 static enum ofperr
851 ofputil_decode_ofpst_request(const struct ofp_header *oh, size_t length,
852                              const struct ofputil_msg_type **typep)
853 {
854     static const struct ofputil_msg_type ofpst_requests[] = {
855         { OFPUTIL_OFPST_DESC_REQUEST, OFP10_VERSION,
856           OFPST_DESC, "OFPST_DESC request",
857           sizeof(struct ofp_stats_msg), 0 },
858
859         { OFPUTIL_OFPST_FLOW_REQUEST, OFP10_VERSION,
860           OFPST_FLOW, "OFPST_FLOW request",
861           sizeof(struct ofp_flow_stats_request), 0 },
862
863         { OFPUTIL_OFPST_AGGREGATE_REQUEST, OFP10_VERSION,
864           OFPST_AGGREGATE, "OFPST_AGGREGATE request",
865           sizeof(struct ofp_flow_stats_request), 0 },
866
867         { OFPUTIL_OFPST_TABLE_REQUEST, OFP10_VERSION,
868           OFPST_TABLE, "OFPST_TABLE request",
869           sizeof(struct ofp_stats_msg), 0 },
870
871         { OFPUTIL_OFPST_PORT_REQUEST, OFP10_VERSION,
872           OFPST_PORT, "OFPST_PORT request",
873           sizeof(struct ofp_port_stats_request), 0 },
874
875         { OFPUTIL_OFPST_QUEUE_REQUEST, OFP10_VERSION,
876           OFPST_QUEUE, "OFPST_QUEUE request",
877           sizeof(struct ofp_queue_stats_request), 0 },
878
879         { OFPUTIL_OFPST_PORT_DESC_REQUEST, OFP10_VERSION,
880           OFPST_PORT_DESC, "OFPST_PORT_DESC request",
881           sizeof(struct ofp_stats_msg), 0 },
882
883         { 0, 0,
884           OFPST_VENDOR, "OFPST_VENDOR request",
885           sizeof(struct ofp_vendor_stats_msg), 1 },
886     };
887
888     static const struct ofputil_msg_category ofpst_request_category = {
889         "OpenFlow statistics",
890         ofpst_requests, ARRAY_SIZE(ofpst_requests),
891         OFPERR_OFPBRC_BAD_STAT
892     };
893
894     const struct ofp_stats_msg *request = (const struct ofp_stats_msg *) oh;
895     enum ofperr error;
896
897     error = check_stats_msg(oh, length);
898     if (error) {
899         return error;
900     }
901
902     error = ofputil_lookup_openflow_message(&ofpst_request_category,
903                                             oh->version, ntohs(request->type),
904                                             typep);
905     if (!error && request->type == htons(OFPST_VENDOR)) {
906         error = ofputil_decode_nxst_request(oh, length, typep);
907     }
908     return error;
909 }
910
911 static enum ofperr
912 ofputil_decode_ofpst_reply(const struct ofp_header *oh, size_t length,
913                            const struct ofputil_msg_type **typep)
914 {
915     static const struct ofputil_msg_type ofpst_replies[] = {
916         { OFPUTIL_OFPST_DESC_REPLY, OFP10_VERSION,
917           OFPST_DESC, "OFPST_DESC reply",
918           sizeof(struct ofp_desc_stats), 0 },
919
920         { OFPUTIL_OFPST_FLOW_REPLY, OFP10_VERSION,
921           OFPST_FLOW, "OFPST_FLOW reply",
922           sizeof(struct ofp_stats_msg), 1 },
923
924         { OFPUTIL_OFPST_AGGREGATE_REPLY, OFP10_VERSION,
925           OFPST_AGGREGATE, "OFPST_AGGREGATE reply",
926           sizeof(struct ofp_aggregate_stats_reply), 0 },
927
928         { OFPUTIL_OFPST_TABLE_REPLY, OFP10_VERSION,
929           OFPST_TABLE, "OFPST_TABLE reply",
930           sizeof(struct ofp_stats_msg), sizeof(struct ofp_table_stats) },
931
932         { OFPUTIL_OFPST_PORT_REPLY, OFP10_VERSION,
933           OFPST_PORT, "OFPST_PORT reply",
934           sizeof(struct ofp_stats_msg), sizeof(struct ofp_port_stats) },
935
936         { OFPUTIL_OFPST_QUEUE_REPLY, OFP10_VERSION,
937           OFPST_QUEUE, "OFPST_QUEUE reply",
938           sizeof(struct ofp_stats_msg), sizeof(struct ofp_queue_stats) },
939
940         { OFPUTIL_OFPST_PORT_DESC_REPLY, OFP10_VERSION,
941           OFPST_PORT_DESC, "OFPST_PORT_DESC reply",
942           sizeof(struct ofp_stats_msg), sizeof(struct ofp10_phy_port) },
943
944         { 0, 0,
945           OFPST_VENDOR, "OFPST_VENDOR reply",
946           sizeof(struct ofp_vendor_stats_msg), 1 },
947     };
948
949     static const struct ofputil_msg_category ofpst_reply_category = {
950         "OpenFlow statistics",
951         ofpst_replies, ARRAY_SIZE(ofpst_replies),
952         OFPERR_OFPBRC_BAD_STAT
953     };
954
955     const struct ofp_stats_msg *reply = (const struct ofp_stats_msg *) oh;
956     enum ofperr error;
957
958     error = check_stats_msg(oh, length);
959     if (error) {
960         return error;
961     }
962
963     error = ofputil_lookup_openflow_message(&ofpst_reply_category, oh->version,
964                                            ntohs(reply->type), typep);
965     if (!error && reply->type == htons(OFPST_VENDOR)) {
966         error = ofputil_decode_nxst_reply(oh, length, typep);
967     }
968     return error;
969 }
970
971 static enum ofperr
972 ofputil_decode_msg_type__(const struct ofp_header *oh, size_t length,
973                           const struct ofputil_msg_type **typep)
974 {
975     static const struct ofputil_msg_type ofpt_messages[] = {
976         { OFPUTIL_OFPT_HELLO, OFP10_VERSION,
977           OFPT_HELLO, "OFPT_HELLO",
978           sizeof(struct ofp_hello), 1 },
979
980         { OFPUTIL_OFPT_ERROR, 0,
981           OFPT_ERROR, "OFPT_ERROR",
982           sizeof(struct ofp_error_msg), 1 },
983
984         { OFPUTIL_OFPT_ECHO_REQUEST, OFP10_VERSION,
985           OFPT_ECHO_REQUEST, "OFPT_ECHO_REQUEST",
986           sizeof(struct ofp_header), 1 },
987
988         { OFPUTIL_OFPT_ECHO_REPLY, OFP10_VERSION,
989           OFPT_ECHO_REPLY, "OFPT_ECHO_REPLY",
990           sizeof(struct ofp_header), 1 },
991
992         { OFPUTIL_OFPT_FEATURES_REQUEST, OFP10_VERSION,
993           OFPT_FEATURES_REQUEST, "OFPT_FEATURES_REQUEST",
994           sizeof(struct ofp_header), 0 },
995
996         { OFPUTIL_OFPT_FEATURES_REPLY, OFP10_VERSION,
997           OFPT_FEATURES_REPLY, "OFPT_FEATURES_REPLY",
998           sizeof(struct ofp_switch_features), sizeof(struct ofp10_phy_port) },
999         { OFPUTIL_OFPT_FEATURES_REPLY, OFP11_VERSION,
1000           OFPT_FEATURES_REPLY, "OFPT_FEATURES_REPLY",
1001           sizeof(struct ofp_switch_features), sizeof(struct ofp11_port) },
1002
1003         { OFPUTIL_OFPT_GET_CONFIG_REQUEST, OFP10_VERSION,
1004           OFPT_GET_CONFIG_REQUEST, "OFPT_GET_CONFIG_REQUEST",
1005           sizeof(struct ofp_header), 0 },
1006
1007         { OFPUTIL_OFPT_GET_CONFIG_REPLY, OFP10_VERSION,
1008           OFPT_GET_CONFIG_REPLY, "OFPT_GET_CONFIG_REPLY",
1009           sizeof(struct ofp_switch_config), 0 },
1010
1011         { OFPUTIL_OFPT_SET_CONFIG, OFP10_VERSION,
1012           OFPT_SET_CONFIG, "OFPT_SET_CONFIG",
1013           sizeof(struct ofp_switch_config), 0 },
1014
1015         { OFPUTIL_OFPT_PACKET_IN, OFP10_VERSION,
1016           OFPT_PACKET_IN, "OFPT_PACKET_IN",
1017           offsetof(struct ofp_packet_in, data), 1 },
1018
1019         { OFPUTIL_OFPT_FLOW_REMOVED, OFP10_VERSION,
1020           OFPT_FLOW_REMOVED, "OFPT_FLOW_REMOVED",
1021           sizeof(struct ofp_flow_removed), 0 },
1022
1023         { OFPUTIL_OFPT_PORT_STATUS, OFP10_VERSION,
1024           OFPT_PORT_STATUS, "OFPT_PORT_STATUS",
1025           sizeof(struct ofp_port_status) + sizeof(struct ofp10_phy_port), 0 },
1026         { OFPUTIL_OFPT_PORT_STATUS, OFP11_VERSION,
1027           OFPT_PORT_STATUS, "OFPT_PORT_STATUS",
1028           sizeof(struct ofp_port_status) + sizeof(struct ofp11_port), 0 },
1029
1030         { OFPUTIL_OFPT_PACKET_OUT, OFP10_VERSION,
1031           OFPT_PACKET_OUT, "OFPT_PACKET_OUT",
1032           sizeof(struct ofp_packet_out), 1 },
1033
1034         { OFPUTIL_OFPT_FLOW_MOD, OFP10_VERSION,
1035           OFPT_FLOW_MOD, "OFPT_FLOW_MOD",
1036           sizeof(struct ofp_flow_mod), 1 },
1037
1038         { OFPUTIL_OFPT_PORT_MOD, OFP10_VERSION,
1039           OFPT10_PORT_MOD, "OFPT_PORT_MOD",
1040           sizeof(struct ofp10_port_mod), 0 },
1041         { OFPUTIL_OFPT_PORT_MOD, OFP11_VERSION,
1042           OFPT11_PORT_MOD, "OFPT_PORT_MOD",
1043           sizeof(struct ofp11_port_mod), 0 },
1044
1045         { 0, OFP10_VERSION,
1046           OFPT10_STATS_REQUEST, "OFPT_STATS_REQUEST",
1047           sizeof(struct ofp_stats_msg), 1 },
1048
1049         { 0, OFP10_VERSION,
1050           OFPT10_STATS_REPLY, "OFPT_STATS_REPLY",
1051           sizeof(struct ofp_stats_msg), 1 },
1052
1053         { OFPUTIL_OFPT_BARRIER_REQUEST, OFP10_VERSION,
1054           OFPT10_BARRIER_REQUEST, "OFPT_BARRIER_REQUEST",
1055           sizeof(struct ofp_header), 0 },
1056
1057         { OFPUTIL_OFPT_BARRIER_REPLY, OFP10_VERSION,
1058           OFPT10_BARRIER_REPLY, "OFPT_BARRIER_REPLY",
1059           sizeof(struct ofp_header), 0 },
1060
1061         { 0, 0,
1062           OFPT_VENDOR, "OFPT_VENDOR",
1063           sizeof(struct ofp_vendor_header), 1 },
1064     };
1065
1066     static const struct ofputil_msg_category ofpt_category = {
1067         "OpenFlow message",
1068         ofpt_messages, ARRAY_SIZE(ofpt_messages),
1069         OFPERR_OFPBRC_BAD_TYPE
1070     };
1071
1072     enum ofperr error;
1073
1074     error = ofputil_lookup_openflow_message(&ofpt_category, oh->version,
1075                                             oh->type, typep);
1076     if (!error) {
1077         switch ((oh->version << 8) | oh->type) {
1078         case (OFP10_VERSION << 8) | OFPT_VENDOR:
1079         case (OFP11_VERSION << 8) | OFPT_VENDOR:
1080             error = ofputil_decode_vendor(oh, length, typep);
1081             break;
1082
1083         case (OFP10_VERSION << 8) | OFPT10_STATS_REQUEST:
1084         case (OFP11_VERSION << 8) | OFPT11_STATS_REQUEST:
1085             error = ofputil_decode_ofpst_request(oh, length, typep);
1086             break;
1087
1088         case (OFP10_VERSION << 8) | OFPT10_STATS_REPLY:
1089         case (OFP11_VERSION << 8) | OFPT11_STATS_REPLY:
1090             error = ofputil_decode_ofpst_reply(oh, length, typep);
1091
1092         default:
1093             break;
1094         }
1095     }
1096     return error;
1097 }
1098
1099 /* Decodes the message type represented by 'oh'.  Returns 0 if successful or an
1100  * OpenFlow error code on failure.  Either way, stores in '*typep' a type
1101  * structure that can be inspected with the ofputil_msg_type_*() functions.
1102  *
1103  * oh->length must indicate the correct length of the message (and must be at
1104  * least sizeof(struct ofp_header)).
1105  *
1106  * Success indicates that 'oh' is at least as long as the minimum-length
1107  * message of its type. */
1108 enum ofperr
1109 ofputil_decode_msg_type(const struct ofp_header *oh,
1110                         const struct ofputil_msg_type **typep)
1111 {
1112     size_t length = ntohs(oh->length);
1113     enum ofperr error;
1114
1115     error = ofputil_decode_msg_type__(oh, length, typep);
1116     if (!error) {
1117         error = ofputil_check_length(*typep, length);
1118     }
1119     if (error) {
1120         *typep = &ofputil_invalid_type;
1121     }
1122     return error;
1123 }
1124
1125 /* Decodes the message type represented by 'oh', of which only the first
1126  * 'length' bytes are available.  Returns 0 if successful or an OpenFlow error
1127  * code on failure.  Either way, stores in '*typep' a type structure that can
1128  * be inspected with the ofputil_msg_type_*() functions.  */
1129 enum ofperr
1130 ofputil_decode_msg_type_partial(const struct ofp_header *oh, size_t length,
1131                                 const struct ofputil_msg_type **typep)
1132 {
1133     enum ofperr error;
1134
1135     error = (length >= sizeof *oh
1136              ? ofputil_decode_msg_type__(oh, length, typep)
1137              : OFPERR_OFPBRC_BAD_LEN);
1138     if (error) {
1139         *typep = &ofputil_invalid_type;
1140     }
1141     return error;
1142 }
1143
1144 /* Returns an OFPUTIL_* message type code for 'type'. */
1145 enum ofputil_msg_code
1146 ofputil_msg_type_code(const struct ofputil_msg_type *type)
1147 {
1148     return type->code;
1149 }
1150 \f
1151 /* Protocols. */
1152
1153 struct proto_abbrev {
1154     enum ofputil_protocol protocol;
1155     const char *name;
1156 };
1157
1158 /* Most users really don't care about some of the differences between
1159  * protocols.  These abbreviations help with that. */
1160 static const struct proto_abbrev proto_abbrevs[] = {
1161     { OFPUTIL_P_ANY,      "any" },
1162     { OFPUTIL_P_OF10_ANY, "OpenFlow10" },
1163     { OFPUTIL_P_NXM_ANY,  "NXM" },
1164 };
1165 #define N_PROTO_ABBREVS ARRAY_SIZE(proto_abbrevs)
1166
1167 enum ofputil_protocol ofputil_flow_dump_protocols[] = {
1168     OFPUTIL_P_NXM,
1169     OFPUTIL_P_OF10,
1170 };
1171 size_t ofputil_n_flow_dump_protocols = ARRAY_SIZE(ofputil_flow_dump_protocols);
1172
1173 /* Returns the ofputil_protocol that is initially in effect on an OpenFlow
1174  * connection that has negotiated the given 'version'.  'version' should
1175  * normally be an 8-bit OpenFlow version identifier (e.g. 0x01 for OpenFlow
1176  * 1.0, 0x02 for OpenFlow 1.1).  Returns 0 if 'version' is not supported or
1177  * outside the valid range.  */
1178 enum ofputil_protocol
1179 ofputil_protocol_from_ofp_version(int version)
1180 {
1181     switch (version) {
1182     case OFP10_VERSION: return OFPUTIL_P_OF10;
1183     default: return 0;
1184     }
1185 }
1186
1187 /* Returns the OpenFlow protocol version number (e.g. OFP10_VERSION or
1188  * OFP11_VERSION) that corresponds to 'protocol'. */
1189 uint8_t
1190 ofputil_protocol_to_ofp_version(enum ofputil_protocol protocol)
1191 {
1192     switch (protocol) {
1193     case OFPUTIL_P_OF10:
1194     case OFPUTIL_P_OF10_TID:
1195     case OFPUTIL_P_NXM:
1196     case OFPUTIL_P_NXM_TID:
1197         return OFP10_VERSION;
1198     }
1199
1200     NOT_REACHED();
1201 }
1202
1203 /* Returns true if 'protocol' is a single OFPUTIL_P_* value, false
1204  * otherwise. */
1205 bool
1206 ofputil_protocol_is_valid(enum ofputil_protocol protocol)
1207 {
1208     return protocol & OFPUTIL_P_ANY && is_pow2(protocol);
1209 }
1210
1211 /* Returns the equivalent of 'protocol' with the Nicira flow_mod_table_id
1212  * extension turned on or off if 'enable' is true or false, respectively.
1213  *
1214  * This extension is only useful for protocols whose "standard" version does
1215  * not allow specific tables to be modified.  In particular, this is true of
1216  * OpenFlow 1.0.  In later versions of OpenFlow, a flow_mod request always
1217  * specifies a table ID and so there is no need for such an extension.  When
1218  * 'protocol' is such a protocol that doesn't need a flow_mod_table_id
1219  * extension, this function just returns its 'protocol' argument unchanged
1220  * regardless of the value of 'enable'.  */
1221 enum ofputil_protocol
1222 ofputil_protocol_set_tid(enum ofputil_protocol protocol, bool enable)
1223 {
1224     switch (protocol) {
1225     case OFPUTIL_P_OF10:
1226     case OFPUTIL_P_OF10_TID:
1227         return enable ? OFPUTIL_P_OF10_TID : OFPUTIL_P_OF10;
1228
1229     case OFPUTIL_P_NXM:
1230     case OFPUTIL_P_NXM_TID:
1231         return enable ? OFPUTIL_P_NXM_TID : OFPUTIL_P_NXM;
1232
1233     default:
1234         NOT_REACHED();
1235     }
1236 }
1237
1238 /* Returns the "base" version of 'protocol'.  That is, if 'protocol' includes
1239  * some extension to a standard protocol version, the return value is the
1240  * standard version of that protocol without any extension.  If 'protocol' is a
1241  * standard protocol version, returns 'protocol' unchanged. */
1242 enum ofputil_protocol
1243 ofputil_protocol_to_base(enum ofputil_protocol protocol)
1244 {
1245     return ofputil_protocol_set_tid(protocol, false);
1246 }
1247
1248 /* Returns 'new_base' with any extensions taken from 'cur'. */
1249 enum ofputil_protocol
1250 ofputil_protocol_set_base(enum ofputil_protocol cur,
1251                           enum ofputil_protocol new_base)
1252 {
1253     bool tid = (cur & OFPUTIL_P_TID) != 0;
1254
1255     switch (new_base) {
1256     case OFPUTIL_P_OF10:
1257     case OFPUTIL_P_OF10_TID:
1258         return ofputil_protocol_set_tid(OFPUTIL_P_OF10, tid);
1259
1260     case OFPUTIL_P_NXM:
1261     case OFPUTIL_P_NXM_TID:
1262         return ofputil_protocol_set_tid(OFPUTIL_P_NXM, tid);
1263
1264     default:
1265         NOT_REACHED();
1266     }
1267 }
1268
1269 /* Returns a string form of 'protocol', if a simple form exists (that is, if
1270  * 'protocol' is either a single protocol or it is a combination of protocols
1271  * that have a single abbreviation).  Otherwise, returns NULL. */
1272 const char *
1273 ofputil_protocol_to_string(enum ofputil_protocol protocol)
1274 {
1275     const struct proto_abbrev *p;
1276
1277     /* Use a "switch" statement for single-bit names so that we get a compiler
1278      * warning if we forget any. */
1279     switch (protocol) {
1280     case OFPUTIL_P_NXM:
1281         return "NXM-table_id";
1282
1283     case OFPUTIL_P_NXM_TID:
1284         return "NXM+table_id";
1285
1286     case OFPUTIL_P_OF10:
1287         return "OpenFlow10-table_id";
1288
1289     case OFPUTIL_P_OF10_TID:
1290         return "OpenFlow10+table_id";
1291     }
1292
1293     /* Check abbreviations. */
1294     for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
1295         if (protocol == p->protocol) {
1296             return p->name;
1297         }
1298     }
1299
1300     return NULL;
1301 }
1302
1303 /* Returns a string that represents 'protocols'.  The return value might be a
1304  * comma-separated list if 'protocols' doesn't have a simple name.  The return
1305  * value is "none" if 'protocols' is 0.
1306  *
1307  * The caller must free the returned string (with free()). */
1308 char *
1309 ofputil_protocols_to_string(enum ofputil_protocol protocols)
1310 {
1311     struct ds s;
1312
1313     assert(!(protocols & ~OFPUTIL_P_ANY));
1314     if (protocols == 0) {
1315         return xstrdup("none");
1316     }
1317
1318     ds_init(&s);
1319     while (protocols) {
1320         const struct proto_abbrev *p;
1321         int i;
1322
1323         if (s.length) {
1324             ds_put_char(&s, ',');
1325         }
1326
1327         for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
1328             if ((protocols & p->protocol) == p->protocol) {
1329                 ds_put_cstr(&s, p->name);
1330                 protocols &= ~p->protocol;
1331                 goto match;
1332             }
1333         }
1334
1335         for (i = 0; i < CHAR_BIT * sizeof(enum ofputil_protocol); i++) {
1336             enum ofputil_protocol bit = 1u << i;
1337
1338             if (protocols & bit) {
1339                 ds_put_cstr(&s, ofputil_protocol_to_string(bit));
1340                 protocols &= ~bit;
1341                 goto match;
1342             }
1343         }
1344         NOT_REACHED();
1345
1346     match: ;
1347     }
1348     return ds_steal_cstr(&s);
1349 }
1350
1351 static enum ofputil_protocol
1352 ofputil_protocol_from_string__(const char *s, size_t n)
1353 {
1354     const struct proto_abbrev *p;
1355     int i;
1356
1357     for (i = 0; i < CHAR_BIT * sizeof(enum ofputil_protocol); i++) {
1358         enum ofputil_protocol bit = 1u << i;
1359         const char *name = ofputil_protocol_to_string(bit);
1360
1361         if (name && n == strlen(name) && !strncasecmp(s, name, n)) {
1362             return bit;
1363         }
1364     }
1365
1366     for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
1367         if (n == strlen(p->name) && !strncasecmp(s, p->name, n)) {
1368             return p->protocol;
1369         }
1370     }
1371
1372     return 0;
1373 }
1374
1375 /* Returns the nonempty set of protocols represented by 's', which can be a
1376  * single protocol name or abbreviation or a comma-separated list of them.
1377  *
1378  * Aborts the program with an error message if 's' is invalid. */
1379 enum ofputil_protocol
1380 ofputil_protocols_from_string(const char *s)
1381 {
1382     const char *orig_s = s;
1383     enum ofputil_protocol protocols;
1384
1385     protocols = 0;
1386     while (*s) {
1387         enum ofputil_protocol p;
1388         size_t n;
1389
1390         n = strcspn(s, ",");
1391         if (n == 0) {
1392             s++;
1393             continue;
1394         }
1395
1396         p = ofputil_protocol_from_string__(s, n);
1397         if (!p) {
1398             ovs_fatal(0, "%.*s: unknown flow protocol", (int) n, s);
1399         }
1400         protocols |= p;
1401
1402         s += n;
1403     }
1404
1405     if (!protocols) {
1406         ovs_fatal(0, "%s: no flow protocol specified", orig_s);
1407     }
1408     return protocols;
1409 }
1410
1411 bool
1412 ofputil_packet_in_format_is_valid(enum nx_packet_in_format packet_in_format)
1413 {
1414     switch (packet_in_format) {
1415     case NXPIF_OPENFLOW10:
1416     case NXPIF_NXM:
1417         return true;
1418     }
1419
1420     return false;
1421 }
1422
1423 const char *
1424 ofputil_packet_in_format_to_string(enum nx_packet_in_format packet_in_format)
1425 {
1426     switch (packet_in_format) {
1427     case NXPIF_OPENFLOW10:
1428         return "openflow10";
1429     case NXPIF_NXM:
1430         return "nxm";
1431     default:
1432         NOT_REACHED();
1433     }
1434 }
1435
1436 int
1437 ofputil_packet_in_format_from_string(const char *s)
1438 {
1439     return (!strcmp(s, "openflow10") ? NXPIF_OPENFLOW10
1440             : !strcmp(s, "nxm") ? NXPIF_NXM
1441             : -1);
1442 }
1443
1444 static bool
1445 regs_fully_wildcarded(const struct flow_wildcards *wc)
1446 {
1447     int i;
1448
1449     for (i = 0; i < FLOW_N_REGS; i++) {
1450         if (wc->reg_masks[i] != 0) {
1451             return false;
1452         }
1453     }
1454     return true;
1455 }
1456
1457 /* Returns a bit-mask of ofputil_protocols that can be used for sending 'rule'
1458  * to a switch (e.g. to add or remove a flow).  Only NXM can handle tunnel IDs,
1459  * registers, or fixing the Ethernet multicast bit.  Otherwise, it's better to
1460  * use OpenFlow 1.0 protocol for backward compatibility. */
1461 enum ofputil_protocol
1462 ofputil_usable_protocols(const struct cls_rule *rule)
1463 {
1464     const struct flow_wildcards *wc = &rule->wc;
1465
1466     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 12);
1467
1468     /* NXM and OF1.1+ supports bitwise matching on ethernet addresses. */
1469     if (!eth_mask_is_exact(wc->dl_src_mask)
1470         && !eth_addr_is_zero(wc->dl_src_mask)) {
1471         return OFPUTIL_P_NXM_ANY;
1472     }
1473     if (!eth_mask_is_exact(wc->dl_dst_mask)
1474         && !eth_addr_is_zero(wc->dl_dst_mask)) {
1475         return OFPUTIL_P_NXM_ANY;
1476     }
1477
1478     /* NXM and OF1.1+ support matching metadata. */
1479     if (wc->metadata_mask != htonll(0)) {
1480         return OFPUTIL_P_NXM_ANY;
1481     }
1482
1483     /* Only NXM supports matching ARP hardware addresses. */
1484     if (!(wc->wildcards & FWW_ARP_SHA) || !(wc->wildcards & FWW_ARP_THA)) {
1485         return OFPUTIL_P_NXM_ANY;
1486     }
1487
1488     /* Only NXM supports matching IPv6 traffic. */
1489     if (!(wc->wildcards & FWW_DL_TYPE)
1490             && (rule->flow.dl_type == htons(ETH_TYPE_IPV6))) {
1491         return OFPUTIL_P_NXM_ANY;
1492     }
1493
1494     /* Only NXM supports matching registers. */
1495     if (!regs_fully_wildcarded(wc)) {
1496         return OFPUTIL_P_NXM_ANY;
1497     }
1498
1499     /* Only NXM supports matching tun_id. */
1500     if (wc->tun_id_mask != htonll(0)) {
1501         return OFPUTIL_P_NXM_ANY;
1502     }
1503
1504     /* Only NXM supports matching fragments. */
1505     if (wc->nw_frag_mask) {
1506         return OFPUTIL_P_NXM_ANY;
1507     }
1508
1509     /* Only NXM supports matching IPv6 flow label. */
1510     if (!(wc->wildcards & FWW_IPV6_LABEL)) {
1511         return OFPUTIL_P_NXM_ANY;
1512     }
1513
1514     /* Only NXM supports matching IP ECN bits. */
1515     if (!(wc->wildcards & FWW_NW_ECN)) {
1516         return OFPUTIL_P_NXM_ANY;
1517     }
1518
1519     /* Only NXM supports matching IP TTL/hop limit. */
1520     if (!(wc->wildcards & FWW_NW_TTL)) {
1521         return OFPUTIL_P_NXM_ANY;
1522     }
1523
1524     /* Only NXM supports non-CIDR IPv4 address masks. */
1525     if (!ip_is_cidr(wc->nw_src_mask) || !ip_is_cidr(wc->nw_dst_mask)) {
1526         return OFPUTIL_P_NXM_ANY;
1527     }
1528
1529     /* Only NXM supports bitwise matching on transport port. */
1530     if ((wc->tp_src_mask && wc->tp_src_mask != htons(UINT16_MAX)) ||
1531         (wc->tp_dst_mask && wc->tp_dst_mask != htons(UINT16_MAX))) {
1532         return OFPUTIL_P_NXM_ANY;
1533     }
1534
1535     /* Other formats can express this rule. */
1536     return OFPUTIL_P_ANY;
1537 }
1538
1539 /* Returns an OpenFlow message that, sent on an OpenFlow connection whose
1540  * protocol is 'current', at least partly transitions the protocol to 'want'.
1541  * Stores in '*next' the protocol that will be in effect on the OpenFlow
1542  * connection if the switch processes the returned message correctly.  (If
1543  * '*next != want' then the caller will have to iterate.)
1544  *
1545  * If 'current == want', returns NULL and stores 'current' in '*next'. */
1546 struct ofpbuf *
1547 ofputil_encode_set_protocol(enum ofputil_protocol current,
1548                             enum ofputil_protocol want,
1549                             enum ofputil_protocol *next)
1550 {
1551     enum ofputil_protocol cur_base, want_base;
1552     bool cur_tid, want_tid;
1553
1554     cur_base = ofputil_protocol_to_base(current);
1555     want_base = ofputil_protocol_to_base(want);
1556     if (cur_base != want_base) {
1557         *next = ofputil_protocol_set_base(current, want_base);
1558
1559         switch (want_base) {
1560         case OFPUTIL_P_NXM:
1561             return ofputil_encode_nx_set_flow_format(NXFF_NXM);
1562
1563         case OFPUTIL_P_OF10:
1564             return ofputil_encode_nx_set_flow_format(NXFF_OPENFLOW10);
1565
1566         case OFPUTIL_P_OF10_TID:
1567         case OFPUTIL_P_NXM_TID:
1568             NOT_REACHED();
1569         }
1570     }
1571
1572     cur_tid = (current & OFPUTIL_P_TID) != 0;
1573     want_tid = (want & OFPUTIL_P_TID) != 0;
1574     if (cur_tid != want_tid) {
1575         *next = ofputil_protocol_set_tid(current, want_tid);
1576         return ofputil_make_flow_mod_table_id(want_tid);
1577     }
1578
1579     assert(current == want);
1580
1581     *next = current;
1582     return NULL;
1583 }
1584
1585 /* Returns an NXT_SET_FLOW_FORMAT message that can be used to set the flow
1586  * format to 'nxff'.  */
1587 struct ofpbuf *
1588 ofputil_encode_nx_set_flow_format(enum nx_flow_format nxff)
1589 {
1590     struct nx_set_flow_format *sff;
1591     struct ofpbuf *msg;
1592
1593     assert(ofputil_nx_flow_format_is_valid(nxff));
1594
1595     sff = make_nxmsg(sizeof *sff, NXT_SET_FLOW_FORMAT, &msg);
1596     sff->format = htonl(nxff);
1597
1598     return msg;
1599 }
1600
1601 /* Returns the base protocol if 'flow_format' is a valid NXFF_* value, false
1602  * otherwise. */
1603 enum ofputil_protocol
1604 ofputil_nx_flow_format_to_protocol(enum nx_flow_format flow_format)
1605 {
1606     switch (flow_format) {
1607     case NXFF_OPENFLOW10:
1608         return OFPUTIL_P_OF10;
1609
1610     case NXFF_NXM:
1611         return OFPUTIL_P_NXM;
1612
1613     default:
1614         return 0;
1615     }
1616 }
1617
1618 /* Returns true if 'flow_format' is a valid NXFF_* value, false otherwise. */
1619 bool
1620 ofputil_nx_flow_format_is_valid(enum nx_flow_format flow_format)
1621 {
1622     return ofputil_nx_flow_format_to_protocol(flow_format) != 0;
1623 }
1624
1625 /* Returns a string version of 'flow_format', which must be a valid NXFF_*
1626  * value. */
1627 const char *
1628 ofputil_nx_flow_format_to_string(enum nx_flow_format flow_format)
1629 {
1630     switch (flow_format) {
1631     case NXFF_OPENFLOW10:
1632         return "openflow10";
1633     case NXFF_NXM:
1634         return "nxm";
1635     default:
1636         NOT_REACHED();
1637     }
1638 }
1639
1640 struct ofpbuf *
1641 ofputil_make_set_packet_in_format(enum nx_packet_in_format packet_in_format)
1642 {
1643     struct nx_set_packet_in_format *spif;
1644     struct ofpbuf *msg;
1645
1646     spif = make_nxmsg(sizeof *spif, NXT_SET_PACKET_IN_FORMAT, &msg);
1647     spif->format = htonl(packet_in_format);
1648
1649     return msg;
1650 }
1651
1652 /* Returns an OpenFlow message that can be used to turn the flow_mod_table_id
1653  * extension on or off (according to 'flow_mod_table_id'). */
1654 struct ofpbuf *
1655 ofputil_make_flow_mod_table_id(bool flow_mod_table_id)
1656 {
1657     struct nx_flow_mod_table_id *nfmti;
1658     struct ofpbuf *msg;
1659
1660     nfmti = make_nxmsg(sizeof *nfmti, NXT_FLOW_MOD_TABLE_ID, &msg);
1661     nfmti->set = flow_mod_table_id;
1662     return msg;
1663 }
1664
1665 /* Converts an OFPT_FLOW_MOD or NXT_FLOW_MOD message 'oh' into an abstract
1666  * flow_mod in 'fm'.  Returns 0 if successful, otherwise an OpenFlow error
1667  * code.
1668  *
1669  * Uses 'ofpacts' to store the abstract OFPACT_* version of 'oh''s actions.
1670  * The caller must initialize 'ofpacts' and retains ownership of it.
1671  * 'fm->ofpacts' will point into the 'ofpacts' buffer.
1672  *
1673  * Does not validate the flow_mod actions.  The caller should do that, with
1674  * ofpacts_check(). */
1675 enum ofperr
1676 ofputil_decode_flow_mod(struct ofputil_flow_mod *fm,
1677                         const struct ofp_header *oh,
1678                         enum ofputil_protocol protocol,
1679                         struct ofpbuf *ofpacts)
1680 {
1681     const struct ofputil_msg_type *type;
1682     uint16_t command;
1683     struct ofpbuf b;
1684
1685     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1686
1687     ofputil_decode_msg_type(oh, &type);
1688     if (ofputil_msg_type_code(type) == OFPUTIL_OFPT_FLOW_MOD) {
1689         /* Standard OpenFlow flow_mod. */
1690         const struct ofp_flow_mod *ofm;
1691         uint16_t priority;
1692         enum ofperr error;
1693
1694         /* Get the ofp_flow_mod. */
1695         ofm = ofpbuf_pull(&b, sizeof *ofm);
1696
1697         /* Set priority based on original wildcards.  Normally we'd allow
1698          * ofputil_cls_rule_from_match() to do this for us, but
1699          * ofputil_normalize_rule() can put wildcards where the original flow
1700          * didn't have them. */
1701         priority = ntohs(ofm->priority);
1702         if (!(ofm->match.wildcards & htonl(OFPFW10_ALL))) {
1703             priority = UINT16_MAX;
1704         }
1705
1706         /* Translate the rule. */
1707         ofputil_cls_rule_from_ofp10_match(&ofm->match, priority, &fm->cr);
1708         ofputil_normalize_rule(&fm->cr);
1709
1710         /* Now get the actions. */
1711         error = ofpacts_pull_openflow10(&b, b.size, ofpacts);
1712         if (error) {
1713             return error;
1714         }
1715
1716         /* Translate the message. */
1717         command = ntohs(ofm->command);
1718         fm->cookie = htonll(0);
1719         fm->cookie_mask = htonll(0);
1720         fm->new_cookie = ofm->cookie;
1721         fm->idle_timeout = ntohs(ofm->idle_timeout);
1722         fm->hard_timeout = ntohs(ofm->hard_timeout);
1723         fm->buffer_id = ntohl(ofm->buffer_id);
1724         fm->out_port = ntohs(ofm->out_port);
1725         fm->flags = ntohs(ofm->flags);
1726     } else if (ofputil_msg_type_code(type) == OFPUTIL_NXT_FLOW_MOD) {
1727         /* Nicira extended flow_mod. */
1728         const struct nx_flow_mod *nfm;
1729         enum ofperr error;
1730
1731         /* Dissect the message. */
1732         nfm = ofpbuf_pull(&b, sizeof *nfm);
1733         error = nx_pull_match(&b, ntohs(nfm->match_len), ntohs(nfm->priority),
1734                               &fm->cr, &fm->cookie, &fm->cookie_mask);
1735         if (error) {
1736             return error;
1737         }
1738         error = ofpacts_pull_openflow10(&b, b.size, ofpacts);
1739         if (error) {
1740             return error;
1741         }
1742
1743         /* Translate the message. */
1744         command = ntohs(nfm->command);
1745         if ((command & 0xff) == OFPFC_ADD && fm->cookie_mask) {
1746             /* Flow additions may only set a new cookie, not match an
1747              * existing cookie. */
1748             return OFPERR_NXBRC_NXM_INVALID;
1749         }
1750         fm->new_cookie = nfm->cookie;
1751         fm->idle_timeout = ntohs(nfm->idle_timeout);
1752         fm->hard_timeout = ntohs(nfm->hard_timeout);
1753         fm->buffer_id = ntohl(nfm->buffer_id);
1754         fm->out_port = ntohs(nfm->out_port);
1755         fm->flags = ntohs(nfm->flags);
1756     } else {
1757         NOT_REACHED();
1758     }
1759
1760     fm->ofpacts = ofpacts->data;
1761     fm->ofpacts_len = ofpacts->size;
1762     if (protocol & OFPUTIL_P_TID) {
1763         fm->command = command & 0xff;
1764         fm->table_id = command >> 8;
1765     } else {
1766         fm->command = command;
1767         fm->table_id = 0xff;
1768     }
1769
1770     return 0;
1771 }
1772
1773 /* Converts 'fm' into an OFPT_FLOW_MOD or NXT_FLOW_MOD message according to
1774  * 'protocol' and returns the message. */
1775 struct ofpbuf *
1776 ofputil_encode_flow_mod(const struct ofputil_flow_mod *fm,
1777                         enum ofputil_protocol protocol)
1778 {
1779     struct ofp_flow_mod *ofm;
1780     struct nx_flow_mod *nfm;
1781     struct ofpbuf *msg;
1782     uint16_t command;
1783     int match_len;
1784
1785     command = (protocol & OFPUTIL_P_TID
1786                ? (fm->command & 0xff) | (fm->table_id << 8)
1787                : fm->command);
1788
1789     switch (protocol) {
1790     case OFPUTIL_P_OF10:
1791     case OFPUTIL_P_OF10_TID:
1792         msg = ofpbuf_new(sizeof *ofm + fm->ofpacts_len);
1793         ofm = put_openflow(sizeof *ofm, OFPT_FLOW_MOD, msg);
1794         ofputil_cls_rule_to_ofp10_match(&fm->cr, &ofm->match);
1795         ofm->cookie = fm->new_cookie;
1796         ofm->command = htons(command);
1797         ofm->idle_timeout = htons(fm->idle_timeout);
1798         ofm->hard_timeout = htons(fm->hard_timeout);
1799         ofm->priority = htons(fm->cr.priority);
1800         ofm->buffer_id = htonl(fm->buffer_id);
1801         ofm->out_port = htons(fm->out_port);
1802         ofm->flags = htons(fm->flags);
1803         break;
1804
1805     case OFPUTIL_P_NXM:
1806     case OFPUTIL_P_NXM_TID:
1807         msg = ofpbuf_new(sizeof *nfm + NXM_TYPICAL_LEN + fm->ofpacts_len);
1808         put_nxmsg(sizeof *nfm, NXT_FLOW_MOD, msg);
1809         nfm = msg->data;
1810         nfm->command = htons(command);
1811         nfm->cookie = fm->new_cookie;
1812         match_len = nx_put_match(msg, false, &fm->cr,
1813                                  fm->cookie, fm->cookie_mask);
1814         nfm = msg->data;
1815         nfm->idle_timeout = htons(fm->idle_timeout);
1816         nfm->hard_timeout = htons(fm->hard_timeout);
1817         nfm->priority = htons(fm->cr.priority);
1818         nfm->buffer_id = htonl(fm->buffer_id);
1819         nfm->out_port = htons(fm->out_port);
1820         nfm->flags = htons(fm->flags);
1821         nfm->match_len = htons(match_len);
1822         break;
1823
1824     default:
1825         NOT_REACHED();
1826     }
1827
1828     if (fm->ofpacts) {
1829         ofpacts_put_openflow10(fm->ofpacts, fm->ofpacts_len, msg);
1830     }
1831     update_openflow_length(msg);
1832     return msg;
1833 }
1834
1835 /* Returns a bitmask with a 1-bit for each protocol that could be used to
1836  * send all of the 'n_fm's flow table modification requests in 'fms', and a
1837  * 0-bit for each protocol that is inadequate.
1838  *
1839  * (The return value will have at least one 1-bit.) */
1840 enum ofputil_protocol
1841 ofputil_flow_mod_usable_protocols(const struct ofputil_flow_mod *fms,
1842                                   size_t n_fms)
1843 {
1844     enum ofputil_protocol usable_protocols;
1845     size_t i;
1846
1847     usable_protocols = OFPUTIL_P_ANY;
1848     for (i = 0; i < n_fms; i++) {
1849         const struct ofputil_flow_mod *fm = &fms[i];
1850
1851         usable_protocols &= ofputil_usable_protocols(&fm->cr);
1852         if (fm->table_id != 0xff) {
1853             usable_protocols &= OFPUTIL_P_TID;
1854         }
1855
1856         /* Matching of the cookie is only supported through NXM. */
1857         if (fm->cookie_mask != htonll(0)) {
1858             usable_protocols &= OFPUTIL_P_NXM_ANY;
1859         }
1860     }
1861     assert(usable_protocols);
1862
1863     return usable_protocols;
1864 }
1865
1866 static enum ofperr
1867 ofputil_decode_ofpst_flow_request(struct ofputil_flow_stats_request *fsr,
1868                                   const struct ofp_header *oh,
1869                                   bool aggregate)
1870 {
1871     const struct ofp_flow_stats_request *ofsr =
1872         (const struct ofp_flow_stats_request *) oh;
1873
1874     fsr->aggregate = aggregate;
1875     ofputil_cls_rule_from_ofp10_match(&ofsr->match, 0, &fsr->match);
1876     fsr->out_port = ntohs(ofsr->out_port);
1877     fsr->table_id = ofsr->table_id;
1878     fsr->cookie = fsr->cookie_mask = htonll(0);
1879
1880     return 0;
1881 }
1882
1883 static enum ofperr
1884 ofputil_decode_nxst_flow_request(struct ofputil_flow_stats_request *fsr,
1885                                  const struct ofp_header *oh,
1886                                  bool aggregate)
1887 {
1888     const struct nx_flow_stats_request *nfsr;
1889     struct ofpbuf b;
1890     enum ofperr error;
1891
1892     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1893
1894     nfsr = ofpbuf_pull(&b, sizeof *nfsr);
1895     error = nx_pull_match(&b, ntohs(nfsr->match_len), 0, &fsr->match,
1896                           &fsr->cookie, &fsr->cookie_mask);
1897     if (error) {
1898         return error;
1899     }
1900     if (b.size) {
1901         return OFPERR_OFPBRC_BAD_LEN;
1902     }
1903
1904     fsr->aggregate = aggregate;
1905     fsr->out_port = ntohs(nfsr->out_port);
1906     fsr->table_id = nfsr->table_id;
1907
1908     return 0;
1909 }
1910
1911 /* Converts an OFPST_FLOW, OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE
1912  * request 'oh', into an abstract flow_stats_request in 'fsr'.  Returns 0 if
1913  * successful, otherwise an OpenFlow error code. */
1914 enum ofperr
1915 ofputil_decode_flow_stats_request(struct ofputil_flow_stats_request *fsr,
1916                                   const struct ofp_header *oh)
1917 {
1918     const struct ofputil_msg_type *type;
1919     struct ofpbuf b;
1920     int code;
1921
1922     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1923
1924     ofputil_decode_msg_type(oh, &type);
1925     code = ofputil_msg_type_code(type);
1926     switch (code) {
1927     case OFPUTIL_OFPST_FLOW_REQUEST:
1928         return ofputil_decode_ofpst_flow_request(fsr, oh, false);
1929
1930     case OFPUTIL_OFPST_AGGREGATE_REQUEST:
1931         return ofputil_decode_ofpst_flow_request(fsr, oh, true);
1932
1933     case OFPUTIL_NXST_FLOW_REQUEST:
1934         return ofputil_decode_nxst_flow_request(fsr, oh, false);
1935
1936     case OFPUTIL_NXST_AGGREGATE_REQUEST:
1937         return ofputil_decode_nxst_flow_request(fsr, oh, true);
1938
1939     default:
1940         /* Hey, the caller lied. */
1941         NOT_REACHED();
1942     }
1943 }
1944
1945 /* Converts abstract flow_stats_request 'fsr' into an OFPST_FLOW,
1946  * OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE request 'oh' according to
1947  * 'protocol', and returns the message. */
1948 struct ofpbuf *
1949 ofputil_encode_flow_stats_request(const struct ofputil_flow_stats_request *fsr,
1950                                   enum ofputil_protocol protocol)
1951 {
1952     struct ofpbuf *msg;
1953
1954     switch (protocol) {
1955     case OFPUTIL_P_OF10:
1956     case OFPUTIL_P_OF10_TID: {
1957         struct ofp_flow_stats_request *ofsr;
1958         int type;
1959
1960         type = fsr->aggregate ? OFPST_AGGREGATE : OFPST_FLOW;
1961         ofsr = ofputil_make_stats_request(sizeof *ofsr, type, 0, &msg);
1962         ofputil_cls_rule_to_ofp10_match(&fsr->match, &ofsr->match);
1963         ofsr->table_id = fsr->table_id;
1964         ofsr->out_port = htons(fsr->out_port);
1965         break;
1966     }
1967
1968     case OFPUTIL_P_NXM:
1969     case OFPUTIL_P_NXM_TID: {
1970         struct nx_flow_stats_request *nfsr;
1971         int match_len;
1972         int subtype;
1973
1974         subtype = fsr->aggregate ? NXST_AGGREGATE : NXST_FLOW;
1975         ofputil_make_stats_request(sizeof *nfsr, OFPST_VENDOR, subtype, &msg);
1976         match_len = nx_put_match(msg, false, &fsr->match,
1977                                  fsr->cookie, fsr->cookie_mask);
1978
1979         nfsr = msg->data;
1980         nfsr->out_port = htons(fsr->out_port);
1981         nfsr->match_len = htons(match_len);
1982         nfsr->table_id = fsr->table_id;
1983         break;
1984     }
1985
1986     default:
1987         NOT_REACHED();
1988     }
1989
1990     return msg;
1991 }
1992
1993 /* Returns a bitmask with a 1-bit for each protocol that could be used to
1994  * accurately encode 'fsr', and a 0-bit for each protocol that is inadequate.
1995  *
1996  * (The return value will have at least one 1-bit.) */
1997 enum ofputil_protocol
1998 ofputil_flow_stats_request_usable_protocols(
1999     const struct ofputil_flow_stats_request *fsr)
2000 {
2001     enum ofputil_protocol usable_protocols;
2002
2003     usable_protocols = ofputil_usable_protocols(&fsr->match);
2004     if (fsr->cookie_mask != htonll(0)) {
2005         usable_protocols &= OFPUTIL_P_NXM_ANY;
2006     }
2007     return usable_protocols;
2008 }
2009
2010 /* Converts an OFPST_FLOW or NXST_FLOW reply in 'msg' into an abstract
2011  * ofputil_flow_stats in 'fs'.
2012  *
2013  * Multiple OFPST_FLOW or NXST_FLOW replies can be packed into a single
2014  * OpenFlow message.  Calling this function multiple times for a single 'msg'
2015  * iterates through the replies.  The caller must initially leave 'msg''s layer
2016  * pointers null and not modify them between calls.
2017  *
2018  * Most switches don't send the values needed to populate fs->idle_age and
2019  * fs->hard_age, so those members will usually be set to 0.  If the switch from
2020  * which 'msg' originated is known to implement NXT_FLOW_AGE, then pass
2021  * 'flow_age_extension' as true so that the contents of 'msg' determine the
2022  * 'idle_age' and 'hard_age' members in 'fs'.
2023  *
2024  * Uses 'ofpacts' to store the abstract OFPACT_* version of the flow stats
2025  * reply's actions.  The caller must initialize 'ofpacts' and retains ownership
2026  * of it.  'fs->ofpacts' will point into the 'ofpacts' buffer.
2027  *
2028  * Returns 0 if successful, EOF if no replies were left in this 'msg',
2029  * otherwise a positive errno value. */
2030 int
2031 ofputil_decode_flow_stats_reply(struct ofputil_flow_stats *fs,
2032                                 struct ofpbuf *msg,
2033                                 bool flow_age_extension,
2034                                 struct ofpbuf *ofpacts)
2035 {
2036     const struct ofputil_msg_type *type;
2037     int code;
2038
2039     ofputil_decode_msg_type(msg->l2 ? msg->l2 : msg->data, &type);
2040     code = ofputil_msg_type_code(type);
2041     if (!msg->l2) {
2042         msg->l2 = msg->data;
2043         if (code == OFPUTIL_OFPST_FLOW_REPLY) {
2044             ofpbuf_pull(msg, sizeof(struct ofp_stats_msg));
2045         } else if (code == OFPUTIL_NXST_FLOW_REPLY) {
2046             ofpbuf_pull(msg, sizeof(struct nicira_stats_msg));
2047         } else {
2048             NOT_REACHED();
2049         }
2050     }
2051
2052     if (!msg->size) {
2053         return EOF;
2054     } else if (code == OFPUTIL_OFPST_FLOW_REPLY) {
2055         const struct ofp_flow_stats *ofs;
2056         size_t length;
2057
2058         ofs = ofpbuf_try_pull(msg, sizeof *ofs);
2059         if (!ofs) {
2060             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply has %zu leftover "
2061                          "bytes at end", msg->size);
2062             return EINVAL;
2063         }
2064
2065         length = ntohs(ofs->length);
2066         if (length < sizeof *ofs) {
2067             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply claims invalid "
2068                          "length %zu", length);
2069             return EINVAL;
2070         }
2071
2072         if (ofpacts_pull_openflow10(msg, length - sizeof *ofs, ofpacts)) {
2073             return EINVAL;
2074         }
2075
2076         fs->cookie = get_32aligned_be64(&ofs->cookie);
2077         ofputil_cls_rule_from_ofp10_match(&ofs->match, ntohs(ofs->priority),
2078                                           &fs->rule);
2079         fs->table_id = ofs->table_id;
2080         fs->duration_sec = ntohl(ofs->duration_sec);
2081         fs->duration_nsec = ntohl(ofs->duration_nsec);
2082         fs->idle_timeout = ntohs(ofs->idle_timeout);
2083         fs->hard_timeout = ntohs(ofs->hard_timeout);
2084         fs->idle_age = -1;
2085         fs->hard_age = -1;
2086         fs->packet_count = ntohll(get_32aligned_be64(&ofs->packet_count));
2087         fs->byte_count = ntohll(get_32aligned_be64(&ofs->byte_count));
2088     } else if (code == OFPUTIL_NXST_FLOW_REPLY) {
2089         const struct nx_flow_stats *nfs;
2090         size_t match_len, actions_len, length;
2091
2092         nfs = ofpbuf_try_pull(msg, sizeof *nfs);
2093         if (!nfs) {
2094             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply has %zu leftover "
2095                          "bytes at end", msg->size);
2096             return EINVAL;
2097         }
2098
2099         length = ntohs(nfs->length);
2100         match_len = ntohs(nfs->match_len);
2101         if (length < sizeof *nfs + ROUND_UP(match_len, 8)) {
2102             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply with match_len=%zu "
2103                          "claims invalid length %zu", match_len, length);
2104             return EINVAL;
2105         }
2106         if (nx_pull_match(msg, match_len, ntohs(nfs->priority), &fs->rule,
2107                           NULL, NULL)) {
2108             return EINVAL;
2109         }
2110
2111         actions_len = length - sizeof *nfs - ROUND_UP(match_len, 8);
2112         if (ofpacts_pull_openflow10(msg, actions_len, ofpacts)) {
2113             return EINVAL;
2114         }
2115
2116         fs->cookie = nfs->cookie;
2117         fs->table_id = nfs->table_id;
2118         fs->duration_sec = ntohl(nfs->duration_sec);
2119         fs->duration_nsec = ntohl(nfs->duration_nsec);
2120         fs->idle_timeout = ntohs(nfs->idle_timeout);
2121         fs->hard_timeout = ntohs(nfs->hard_timeout);
2122         fs->idle_age = -1;
2123         fs->hard_age = -1;
2124         if (flow_age_extension) {
2125             if (nfs->idle_age) {
2126                 fs->idle_age = ntohs(nfs->idle_age) - 1;
2127             }
2128             if (nfs->hard_age) {
2129                 fs->hard_age = ntohs(nfs->hard_age) - 1;
2130             }
2131         }
2132         fs->packet_count = ntohll(nfs->packet_count);
2133         fs->byte_count = ntohll(nfs->byte_count);
2134     } else {
2135         NOT_REACHED();
2136     }
2137
2138     fs->ofpacts = ofpacts->data;
2139     fs->ofpacts_len = ofpacts->size;
2140
2141     return 0;
2142 }
2143
2144 /* Returns 'count' unchanged except that UINT64_MAX becomes 0.
2145  *
2146  * We use this in situations where OVS internally uses UINT64_MAX to mean
2147  * "value unknown" but OpenFlow 1.0 does not define any unknown value. */
2148 static uint64_t
2149 unknown_to_zero(uint64_t count)
2150 {
2151     return count != UINT64_MAX ? count : 0;
2152 }
2153
2154 /* Appends an OFPST_FLOW or NXST_FLOW reply that contains the data in 'fs' to
2155  * those already present in the list of ofpbufs in 'replies'.  'replies' should
2156  * have been initialized with ofputil_start_stats_reply(). */
2157 void
2158 ofputil_append_flow_stats_reply(const struct ofputil_flow_stats *fs,
2159                                 struct list *replies)
2160 {
2161     struct ofpbuf *reply = ofpbuf_from_list(list_back(replies));
2162     const struct ofp_stats_msg *osm = reply->data;
2163     size_t start_ofs = reply->size;
2164
2165     if (osm->type == htons(OFPST_FLOW)) {
2166         struct ofp_flow_stats *ofs;
2167
2168         ofpbuf_put_uninit(reply, sizeof *ofs);
2169         ofpacts_put_openflow10(fs->ofpacts, fs->ofpacts_len, reply);
2170
2171         ofs = ofpbuf_at_assert(reply, start_ofs, sizeof *ofs);
2172         ofs->length = htons(reply->size - start_ofs);
2173         ofs->table_id = fs->table_id;
2174         ofs->pad = 0;
2175         ofputil_cls_rule_to_ofp10_match(&fs->rule, &ofs->match);
2176         ofs->duration_sec = htonl(fs->duration_sec);
2177         ofs->duration_nsec = htonl(fs->duration_nsec);
2178         ofs->priority = htons(fs->rule.priority);
2179         ofs->idle_timeout = htons(fs->idle_timeout);
2180         ofs->hard_timeout = htons(fs->hard_timeout);
2181         memset(ofs->pad2, 0, sizeof ofs->pad2);
2182         put_32aligned_be64(&ofs->cookie, fs->cookie);
2183         put_32aligned_be64(&ofs->packet_count,
2184                            htonll(unknown_to_zero(fs->packet_count)));
2185         put_32aligned_be64(&ofs->byte_count,
2186                            htonll(unknown_to_zero(fs->byte_count)));
2187     } else if (osm->type == htons(OFPST_VENDOR)) {
2188         struct nx_flow_stats *nfs;
2189         int match_len;
2190
2191         ofpbuf_put_uninit(reply, sizeof *nfs);
2192         match_len = nx_put_match(reply, false, &fs->rule, 0, 0);
2193         ofpacts_put_openflow10(fs->ofpacts, fs->ofpacts_len, reply);
2194
2195         nfs = ofpbuf_at_assert(reply, start_ofs, sizeof *nfs);
2196         nfs->length = htons(reply->size - start_ofs);
2197         nfs->table_id = fs->table_id;
2198         nfs->pad = 0;
2199         nfs->duration_sec = htonl(fs->duration_sec);
2200         nfs->duration_nsec = htonl(fs->duration_nsec);
2201         nfs->priority = htons(fs->rule.priority);
2202         nfs->idle_timeout = htons(fs->idle_timeout);
2203         nfs->hard_timeout = htons(fs->hard_timeout);
2204         nfs->idle_age = htons(fs->idle_age < 0 ? 0
2205                               : fs->idle_age < UINT16_MAX ? fs->idle_age + 1
2206                               : UINT16_MAX);
2207         nfs->hard_age = htons(fs->hard_age < 0 ? 0
2208                               : fs->hard_age < UINT16_MAX ? fs->hard_age + 1
2209                               : UINT16_MAX);
2210         nfs->match_len = htons(match_len);
2211         nfs->cookie = fs->cookie;
2212         nfs->packet_count = htonll(fs->packet_count);
2213         nfs->byte_count = htonll(fs->byte_count);
2214     } else {
2215         NOT_REACHED();
2216     }
2217
2218     ofputil_postappend_stats_reply(start_ofs, replies);
2219 }
2220
2221 /* Converts abstract ofputil_aggregate_stats 'stats' into an OFPST_AGGREGATE or
2222  * NXST_AGGREGATE reply according to 'protocol', and returns the message. */
2223 struct ofpbuf *
2224 ofputil_encode_aggregate_stats_reply(
2225     const struct ofputil_aggregate_stats *stats,
2226     const struct ofp_stats_msg *request)
2227 {
2228     struct ofpbuf *msg;
2229
2230     if (request->type == htons(OFPST_AGGREGATE)) {
2231         struct ofp_aggregate_stats_reply *asr;
2232
2233         asr = ofputil_make_stats_reply(sizeof *asr, request, &msg);
2234         put_32aligned_be64(&asr->packet_count,
2235                            htonll(unknown_to_zero(stats->packet_count)));
2236         put_32aligned_be64(&asr->byte_count,
2237                            htonll(unknown_to_zero(stats->byte_count)));
2238         asr->flow_count = htonl(stats->flow_count);
2239     } else if (request->type == htons(OFPST_VENDOR)) {
2240         struct nx_aggregate_stats_reply *nasr;
2241
2242         nasr = ofputil_make_stats_reply(sizeof *nasr, request, &msg);
2243         assert(nasr->nsm.subtype == htonl(NXST_AGGREGATE));
2244         nasr->packet_count = htonll(stats->packet_count);
2245         nasr->byte_count = htonll(stats->byte_count);
2246         nasr->flow_count = htonl(stats->flow_count);
2247     } else {
2248         NOT_REACHED();
2249     }
2250
2251     return msg;
2252 }
2253
2254 /* Converts an OFPT_FLOW_REMOVED or NXT_FLOW_REMOVED message 'oh' into an
2255  * abstract ofputil_flow_removed in 'fr'.  Returns 0 if successful, otherwise
2256  * an OpenFlow error code. */
2257 enum ofperr
2258 ofputil_decode_flow_removed(struct ofputil_flow_removed *fr,
2259                             const struct ofp_header *oh)
2260 {
2261     const struct ofputil_msg_type *type;
2262     enum ofputil_msg_code code;
2263
2264     ofputil_decode_msg_type(oh, &type);
2265     code = ofputil_msg_type_code(type);
2266     if (code == OFPUTIL_OFPT_FLOW_REMOVED) {
2267         const struct ofp_flow_removed *ofr;
2268
2269         ofr = (const struct ofp_flow_removed *) oh;
2270         ofputil_cls_rule_from_ofp10_match(&ofr->match, ntohs(ofr->priority),
2271                                           &fr->rule);
2272         fr->cookie = ofr->cookie;
2273         fr->reason = ofr->reason;
2274         fr->duration_sec = ntohl(ofr->duration_sec);
2275         fr->duration_nsec = ntohl(ofr->duration_nsec);
2276         fr->idle_timeout = ntohs(ofr->idle_timeout);
2277         fr->packet_count = ntohll(ofr->packet_count);
2278         fr->byte_count = ntohll(ofr->byte_count);
2279     } else if (code == OFPUTIL_NXT_FLOW_REMOVED) {
2280         struct nx_flow_removed *nfr;
2281         struct ofpbuf b;
2282         int error;
2283
2284         ofpbuf_use_const(&b, oh, ntohs(oh->length));
2285
2286         nfr = ofpbuf_pull(&b, sizeof *nfr);
2287         error = nx_pull_match(&b, ntohs(nfr->match_len), ntohs(nfr->priority),
2288                               &fr->rule, NULL, NULL);
2289         if (error) {
2290             return error;
2291         }
2292         if (b.size) {
2293             return OFPERR_OFPBRC_BAD_LEN;
2294         }
2295
2296         fr->cookie = nfr->cookie;
2297         fr->reason = nfr->reason;
2298         fr->duration_sec = ntohl(nfr->duration_sec);
2299         fr->duration_nsec = ntohl(nfr->duration_nsec);
2300         fr->idle_timeout = ntohs(nfr->idle_timeout);
2301         fr->packet_count = ntohll(nfr->packet_count);
2302         fr->byte_count = ntohll(nfr->byte_count);
2303     } else {
2304         NOT_REACHED();
2305     }
2306
2307     return 0;
2308 }
2309
2310 /* Converts abstract ofputil_flow_removed 'fr' into an OFPT_FLOW_REMOVED or
2311  * NXT_FLOW_REMOVED message 'oh' according to 'protocol', and returns the
2312  * message. */
2313 struct ofpbuf *
2314 ofputil_encode_flow_removed(const struct ofputil_flow_removed *fr,
2315                             enum ofputil_protocol protocol)
2316 {
2317     struct ofpbuf *msg;
2318
2319     switch (protocol) {
2320     case OFPUTIL_P_OF10:
2321     case OFPUTIL_P_OF10_TID: {
2322         struct ofp_flow_removed *ofr;
2323
2324         ofr = make_openflow_xid(sizeof *ofr, OFPT_FLOW_REMOVED, htonl(0),
2325                                 &msg);
2326         ofputil_cls_rule_to_ofp10_match(&fr->rule, &ofr->match);
2327         ofr->cookie = fr->cookie;
2328         ofr->priority = htons(fr->rule.priority);
2329         ofr->reason = fr->reason;
2330         ofr->duration_sec = htonl(fr->duration_sec);
2331         ofr->duration_nsec = htonl(fr->duration_nsec);
2332         ofr->idle_timeout = htons(fr->idle_timeout);
2333         ofr->packet_count = htonll(unknown_to_zero(fr->packet_count));
2334         ofr->byte_count = htonll(unknown_to_zero(fr->byte_count));
2335         break;
2336     }
2337
2338     case OFPUTIL_P_NXM:
2339     case OFPUTIL_P_NXM_TID: {
2340         struct nx_flow_removed *nfr;
2341         int match_len;
2342
2343         make_nxmsg_xid(sizeof *nfr, NXT_FLOW_REMOVED, htonl(0), &msg);
2344         match_len = nx_put_match(msg, false, &fr->rule, 0, 0);
2345
2346         nfr = msg->data;
2347         nfr->cookie = fr->cookie;
2348         nfr->priority = htons(fr->rule.priority);
2349         nfr->reason = fr->reason;
2350         nfr->duration_sec = htonl(fr->duration_sec);
2351         nfr->duration_nsec = htonl(fr->duration_nsec);
2352         nfr->idle_timeout = htons(fr->idle_timeout);
2353         nfr->match_len = htons(match_len);
2354         nfr->packet_count = htonll(fr->packet_count);
2355         nfr->byte_count = htonll(fr->byte_count);
2356         break;
2357     }
2358
2359     default:
2360         NOT_REACHED();
2361     }
2362
2363     return msg;
2364 }
2365
2366 enum ofperr
2367 ofputil_decode_packet_in(struct ofputil_packet_in *pin,
2368                          const struct ofp_header *oh)
2369 {
2370     const struct ofputil_msg_type *type;
2371     enum ofputil_msg_code code;
2372
2373     ofputil_decode_msg_type(oh, &type);
2374     code = ofputil_msg_type_code(type);
2375     memset(pin, 0, sizeof *pin);
2376
2377     if (code == OFPUTIL_OFPT_PACKET_IN) {
2378         const struct ofp_packet_in *opi = (const struct ofp_packet_in *) oh;
2379
2380         pin->packet = opi->data;
2381         pin->packet_len = ntohs(opi->header.length)
2382             - offsetof(struct ofp_packet_in, data);
2383
2384         pin->fmd.in_port = ntohs(opi->in_port);
2385         pin->reason = opi->reason;
2386         pin->buffer_id = ntohl(opi->buffer_id);
2387         pin->total_len = ntohs(opi->total_len);
2388     } else if (code == OFPUTIL_NXT_PACKET_IN) {
2389         const struct nx_packet_in *npi;
2390         struct cls_rule rule;
2391         struct ofpbuf b;
2392         int error;
2393
2394         ofpbuf_use_const(&b, oh, ntohs(oh->length));
2395
2396         npi = ofpbuf_pull(&b, sizeof *npi);
2397         error = nx_pull_match_loose(&b, ntohs(npi->match_len), 0, &rule, NULL,
2398                                     NULL);
2399         if (error) {
2400             return error;
2401         }
2402
2403         if (!ofpbuf_try_pull(&b, 2)) {
2404             return OFPERR_OFPBRC_BAD_LEN;
2405         }
2406
2407         pin->packet = b.data;
2408         pin->packet_len = b.size;
2409         pin->reason = npi->reason;
2410         pin->table_id = npi->table_id;
2411         pin->cookie = npi->cookie;
2412
2413         pin->fmd.in_port = rule.flow.in_port;
2414
2415         pin->fmd.tun_id = rule.flow.tun_id;
2416         pin->fmd.tun_id_mask = rule.wc.tun_id_mask;
2417
2418         pin->fmd.metadata = rule.flow.metadata;
2419         pin->fmd.metadata_mask = rule.wc.metadata_mask;
2420
2421         memcpy(pin->fmd.regs, rule.flow.regs, sizeof pin->fmd.regs);
2422         memcpy(pin->fmd.reg_masks, rule.wc.reg_masks,
2423                sizeof pin->fmd.reg_masks);
2424
2425         pin->buffer_id = ntohl(npi->buffer_id);
2426         pin->total_len = ntohs(npi->total_len);
2427     } else {
2428         NOT_REACHED();
2429     }
2430
2431     return 0;
2432 }
2433
2434 /* Converts abstract ofputil_packet_in 'pin' into a PACKET_IN message
2435  * in the format specified by 'packet_in_format'.  */
2436 struct ofpbuf *
2437 ofputil_encode_packet_in(const struct ofputil_packet_in *pin,
2438                          enum nx_packet_in_format packet_in_format)
2439 {
2440     size_t send_len = MIN(pin->send_len, pin->packet_len);
2441     struct ofpbuf *packet;
2442
2443     /* Add OFPT_PACKET_IN. */
2444     if (packet_in_format == NXPIF_OPENFLOW10) {
2445         size_t header_len = offsetof(struct ofp_packet_in, data);
2446         struct ofp_packet_in *opi;
2447
2448         packet = ofpbuf_new(send_len + header_len);
2449         opi = ofpbuf_put_zeros(packet, header_len);
2450         opi->header.version = OFP10_VERSION;
2451         opi->header.type = OFPT_PACKET_IN;
2452         opi->total_len = htons(pin->total_len);
2453         opi->in_port = htons(pin->fmd.in_port);
2454         opi->reason = pin->reason;
2455         opi->buffer_id = htonl(pin->buffer_id);
2456
2457         ofpbuf_put(packet, pin->packet, send_len);
2458     } else if (packet_in_format == NXPIF_NXM) {
2459         struct nx_packet_in *npi;
2460         struct cls_rule rule;
2461         size_t match_len;
2462         size_t i;
2463
2464         /* Estimate of required PACKET_IN length includes the NPI header, space
2465          * for the match (2 times sizeof the metadata seems like enough), 2
2466          * bytes for padding, and the packet length. */
2467         packet = ofpbuf_new(sizeof *npi + sizeof(struct flow_metadata) * 2
2468                             + 2 + send_len);
2469
2470         cls_rule_init_catchall(&rule, 0);
2471         cls_rule_set_tun_id_masked(&rule, pin->fmd.tun_id,
2472                                    pin->fmd.tun_id_mask);
2473         cls_rule_set_metadata_masked(&rule, pin->fmd.metadata,
2474                                    pin->fmd.metadata_mask);
2475
2476
2477         for (i = 0; i < FLOW_N_REGS; i++) {
2478             cls_rule_set_reg_masked(&rule, i, pin->fmd.regs[i],
2479                                     pin->fmd.reg_masks[i]);
2480         }
2481
2482         cls_rule_set_in_port(&rule, pin->fmd.in_port);
2483
2484         ofpbuf_put_zeros(packet, sizeof *npi);
2485         match_len = nx_put_match(packet, false, &rule, 0, 0);
2486         ofpbuf_put_zeros(packet, 2);
2487         ofpbuf_put(packet, pin->packet, send_len);
2488
2489         npi = packet->data;
2490         npi->nxh.header.version = OFP10_VERSION;
2491         npi->nxh.header.type = OFPT_VENDOR;
2492         npi->nxh.vendor = htonl(NX_VENDOR_ID);
2493         npi->nxh.subtype = htonl(NXT_PACKET_IN);
2494
2495         npi->buffer_id = htonl(pin->buffer_id);
2496         npi->total_len = htons(pin->total_len);
2497         npi->reason = pin->reason;
2498         npi->table_id = pin->table_id;
2499         npi->cookie = pin->cookie;
2500         npi->match_len = htons(match_len);
2501     } else {
2502         NOT_REACHED();
2503     }
2504     update_openflow_length(packet);
2505
2506     return packet;
2507 }
2508
2509 const char *
2510 ofputil_packet_in_reason_to_string(enum ofp_packet_in_reason reason)
2511 {
2512     static char s[INT_STRLEN(int) + 1];
2513
2514     switch (reason) {
2515     case OFPR_NO_MATCH:
2516         return "no_match";
2517     case OFPR_ACTION:
2518         return "action";
2519     case OFPR_INVALID_TTL:
2520         return "invalid_ttl";
2521
2522     case OFPR_N_REASONS:
2523     default:
2524         sprintf(s, "%d", (int) reason);
2525         return s;
2526     }
2527 }
2528
2529 bool
2530 ofputil_packet_in_reason_from_string(const char *s,
2531                                      enum ofp_packet_in_reason *reason)
2532 {
2533     int i;
2534
2535     for (i = 0; i < OFPR_N_REASONS; i++) {
2536         if (!strcasecmp(s, ofputil_packet_in_reason_to_string(i))) {
2537             *reason = i;
2538             return true;
2539         }
2540     }
2541     return false;
2542 }
2543
2544 /* Converts an OFPT_PACKET_OUT in 'opo' into an abstract ofputil_packet_out in
2545  * 'po'.
2546  *
2547  * Uses 'ofpacts' to store the abstract OFPACT_* version of the packet out
2548  * message's actions.  The caller must initialize 'ofpacts' and retains
2549  * ownership of it.  'po->ofpacts' will point into the 'ofpacts' buffer.
2550  *
2551  * Returns 0 if successful, otherwise an OFPERR_* value. */
2552 enum ofperr
2553 ofputil_decode_packet_out(struct ofputil_packet_out *po,
2554                           const struct ofp_packet_out *opo,
2555                           struct ofpbuf *ofpacts)
2556 {
2557     enum ofperr error;
2558     struct ofpbuf b;
2559
2560     po->buffer_id = ntohl(opo->buffer_id);
2561     po->in_port = ntohs(opo->in_port);
2562     if (po->in_port >= OFPP_MAX && po->in_port != OFPP_LOCAL
2563         && po->in_port != OFPP_NONE && po->in_port != OFPP_CONTROLLER) {
2564         VLOG_WARN_RL(&bad_ofmsg_rl, "packet-out has bad input port %#"PRIx16,
2565                      po->in_port);
2566         return OFPERR_NXBRC_BAD_IN_PORT;
2567     }
2568
2569     ofpbuf_use_const(&b, opo, ntohs(opo->header.length));
2570     ofpbuf_pull(&b, sizeof *opo);
2571
2572     error = ofpacts_pull_openflow10(&b, ntohs(opo->actions_len), ofpacts);
2573     if (error) {
2574         return error;
2575     }
2576     po->ofpacts = ofpacts->data;
2577     po->ofpacts_len = ofpacts->size;
2578
2579     if (po->buffer_id == UINT32_MAX) {
2580         po->packet = b.data;
2581         po->packet_len = b.size;
2582     } else {
2583         po->packet = NULL;
2584         po->packet_len = 0;
2585     }
2586
2587     return 0;
2588 }
2589 \f
2590 /* ofputil_phy_port */
2591
2592 /* NETDEV_F_* to and from OFPPF_* and OFPPF10_*. */
2593 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_HD    == OFPPF_10MB_HD);  /* bit 0 */
2594 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_FD    == OFPPF_10MB_FD);  /* bit 1 */
2595 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_HD   == OFPPF_100MB_HD); /* bit 2 */
2596 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_FD   == OFPPF_100MB_FD); /* bit 3 */
2597 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_HD     == OFPPF_1GB_HD);   /* bit 4 */
2598 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_FD     == OFPPF_1GB_FD);   /* bit 5 */
2599 BUILD_ASSERT_DECL((int) NETDEV_F_10GB_FD    == OFPPF_10GB_FD);  /* bit 6 */
2600
2601 /* NETDEV_F_ bits 11...15 are OFPPF10_ bits 7...11: */
2602 BUILD_ASSERT_DECL((int) NETDEV_F_COPPER == (OFPPF10_COPPER << 4));
2603 BUILD_ASSERT_DECL((int) NETDEV_F_FIBER == (OFPPF10_FIBER << 4));
2604 BUILD_ASSERT_DECL((int) NETDEV_F_AUTONEG == (OFPPF10_AUTONEG << 4));
2605 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE == (OFPPF10_PAUSE << 4));
2606 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE_ASYM == (OFPPF10_PAUSE_ASYM << 4));
2607
2608 static enum netdev_features
2609 netdev_port_features_from_ofp10(ovs_be32 ofp10_)
2610 {
2611     uint32_t ofp10 = ntohl(ofp10_);
2612     return (ofp10 & 0x7f) | ((ofp10 & 0xf80) << 4);
2613 }
2614
2615 static ovs_be32
2616 netdev_port_features_to_ofp10(enum netdev_features features)
2617 {
2618     return htonl((features & 0x7f) | ((features & 0xf800) >> 4));
2619 }
2620
2621 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_HD    == OFPPF_10MB_HD);     /* bit 0 */
2622 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_FD    == OFPPF_10MB_FD);     /* bit 1 */
2623 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_HD   == OFPPF_100MB_HD);    /* bit 2 */
2624 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_FD   == OFPPF_100MB_FD);    /* bit 3 */
2625 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_HD     == OFPPF_1GB_HD);      /* bit 4 */
2626 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_FD     == OFPPF_1GB_FD);      /* bit 5 */
2627 BUILD_ASSERT_DECL((int) NETDEV_F_10GB_FD    == OFPPF_10GB_FD);     /* bit 6 */
2628 BUILD_ASSERT_DECL((int) NETDEV_F_40GB_FD    == OFPPF11_40GB_FD);   /* bit 7 */
2629 BUILD_ASSERT_DECL((int) NETDEV_F_100GB_FD   == OFPPF11_100GB_FD);  /* bit 8 */
2630 BUILD_ASSERT_DECL((int) NETDEV_F_1TB_FD     == OFPPF11_1TB_FD);    /* bit 9 */
2631 BUILD_ASSERT_DECL((int) NETDEV_F_OTHER      == OFPPF11_OTHER);     /* bit 10 */
2632 BUILD_ASSERT_DECL((int) NETDEV_F_COPPER     == OFPPF11_COPPER);    /* bit 11 */
2633 BUILD_ASSERT_DECL((int) NETDEV_F_FIBER      == OFPPF11_FIBER);     /* bit 12 */
2634 BUILD_ASSERT_DECL((int) NETDEV_F_AUTONEG    == OFPPF11_AUTONEG);   /* bit 13 */
2635 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE      == OFPPF11_PAUSE);     /* bit 14 */
2636 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE_ASYM == OFPPF11_PAUSE_ASYM);/* bit 15 */
2637
2638 static enum netdev_features
2639 netdev_port_features_from_ofp11(ovs_be32 ofp11)
2640 {
2641     return ntohl(ofp11) & 0xffff;
2642 }
2643
2644 static ovs_be32
2645 netdev_port_features_to_ofp11(enum netdev_features features)
2646 {
2647     return htonl(features & 0xffff);
2648 }
2649
2650 static enum ofperr
2651 ofputil_decode_ofp10_phy_port(struct ofputil_phy_port *pp,
2652                               const struct ofp10_phy_port *opp)
2653 {
2654     memset(pp, 0, sizeof *pp);
2655
2656     pp->port_no = ntohs(opp->port_no);
2657     memcpy(pp->hw_addr, opp->hw_addr, OFP_ETH_ALEN);
2658     ovs_strlcpy(pp->name, opp->name, OFP_MAX_PORT_NAME_LEN);
2659
2660     pp->config = ntohl(opp->config) & OFPPC10_ALL;
2661     pp->state = ntohl(opp->state) & OFPPS10_ALL;
2662
2663     pp->curr = netdev_port_features_from_ofp10(opp->curr);
2664     pp->advertised = netdev_port_features_from_ofp10(opp->advertised);
2665     pp->supported = netdev_port_features_from_ofp10(opp->supported);
2666     pp->peer = netdev_port_features_from_ofp10(opp->peer);
2667
2668     pp->curr_speed = netdev_features_to_bps(pp->curr) / 1000;
2669     pp->max_speed = netdev_features_to_bps(pp->supported) / 1000;
2670
2671     return 0;
2672 }
2673
2674 static enum ofperr
2675 ofputil_decode_ofp11_port(struct ofputil_phy_port *pp,
2676                           const struct ofp11_port *op)
2677 {
2678     enum ofperr error;
2679
2680     memset(pp, 0, sizeof *pp);
2681
2682     error = ofputil_port_from_ofp11(op->port_no, &pp->port_no);
2683     if (error) {
2684         return error;
2685     }
2686     memcpy(pp->hw_addr, op->hw_addr, OFP_ETH_ALEN);
2687     ovs_strlcpy(pp->name, op->name, OFP_MAX_PORT_NAME_LEN);
2688
2689     pp->config = ntohl(op->config) & OFPPC11_ALL;
2690     pp->state = ntohl(op->state) & OFPPC11_ALL;
2691
2692     pp->curr = netdev_port_features_from_ofp11(op->curr);
2693     pp->advertised = netdev_port_features_from_ofp11(op->advertised);
2694     pp->supported = netdev_port_features_from_ofp11(op->supported);
2695     pp->peer = netdev_port_features_from_ofp11(op->peer);
2696
2697     pp->curr_speed = ntohl(op->curr_speed);
2698     pp->max_speed = ntohl(op->max_speed);
2699
2700     return 0;
2701 }
2702
2703 static size_t
2704 ofputil_get_phy_port_size(uint8_t ofp_version)
2705 {
2706     return ofp_version == OFP10_VERSION ? sizeof(struct ofp10_phy_port)
2707                                         : sizeof(struct ofp11_port);
2708 }
2709
2710 static void
2711 ofputil_encode_ofp10_phy_port(const struct ofputil_phy_port *pp,
2712                               struct ofp10_phy_port *opp)
2713 {
2714     memset(opp, 0, sizeof *opp);
2715
2716     opp->port_no = htons(pp->port_no);
2717     memcpy(opp->hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2718     ovs_strlcpy(opp->name, pp->name, OFP_MAX_PORT_NAME_LEN);
2719
2720     opp->config = htonl(pp->config & OFPPC10_ALL);
2721     opp->state = htonl(pp->state & OFPPS10_ALL);
2722
2723     opp->curr = netdev_port_features_to_ofp10(pp->curr);
2724     opp->advertised = netdev_port_features_to_ofp10(pp->advertised);
2725     opp->supported = netdev_port_features_to_ofp10(pp->supported);
2726     opp->peer = netdev_port_features_to_ofp10(pp->peer);
2727 }
2728
2729 static void
2730 ofputil_encode_ofp11_port(const struct ofputil_phy_port *pp,
2731                           struct ofp11_port *op)
2732 {
2733     memset(op, 0, sizeof *op);
2734
2735     op->port_no = ofputil_port_to_ofp11(pp->port_no);
2736     memcpy(op->hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2737     ovs_strlcpy(op->name, pp->name, OFP_MAX_PORT_NAME_LEN);
2738
2739     op->config = htonl(pp->config & OFPPC11_ALL);
2740     op->state = htonl(pp->state & OFPPS11_ALL);
2741
2742     op->curr = netdev_port_features_to_ofp11(pp->curr);
2743     op->advertised = netdev_port_features_to_ofp11(pp->advertised);
2744     op->supported = netdev_port_features_to_ofp11(pp->supported);
2745     op->peer = netdev_port_features_to_ofp11(pp->peer);
2746
2747     op->curr_speed = htonl(pp->curr_speed);
2748     op->max_speed = htonl(pp->max_speed);
2749 }
2750
2751 static void
2752 ofputil_put_phy_port(uint8_t ofp_version, const struct ofputil_phy_port *pp,
2753                      struct ofpbuf *b)
2754 {
2755     if (ofp_version == OFP10_VERSION) {
2756         struct ofp10_phy_port *opp;
2757         if (b->size + sizeof *opp <= UINT16_MAX) {
2758             opp = ofpbuf_put_uninit(b, sizeof *opp);
2759             ofputil_encode_ofp10_phy_port(pp, opp);
2760         }
2761     } else {
2762         struct ofp11_port *op;
2763         if (b->size + sizeof *op <= UINT16_MAX) {
2764             op = ofpbuf_put_uninit(b, sizeof *op);
2765             ofputil_encode_ofp11_port(pp, op);
2766         }
2767     }
2768 }
2769
2770 void
2771 ofputil_append_port_desc_stats_reply(uint8_t ofp_version,
2772                                      const struct ofputil_phy_port *pp,
2773                                      struct list *replies)
2774 {
2775     if (ofp_version == OFP10_VERSION) {
2776         struct ofp10_phy_port *opp;
2777
2778         opp = ofputil_append_stats_reply(sizeof *opp, replies);
2779         ofputil_encode_ofp10_phy_port(pp, opp);
2780     } else {
2781         struct ofp11_port *op;
2782
2783         op = ofputil_append_stats_reply(sizeof *op, replies);
2784         ofputil_encode_ofp11_port(pp, op);
2785     }
2786 }
2787 \f
2788 /* ofputil_switch_features */
2789
2790 #define OFPC_COMMON (OFPC_FLOW_STATS | OFPC_TABLE_STATS | OFPC_PORT_STATS | \
2791                      OFPC_IP_REASM | OFPC_QUEUE_STATS | OFPC_ARP_MATCH_IP)
2792 BUILD_ASSERT_DECL((int) OFPUTIL_C_FLOW_STATS == OFPC_FLOW_STATS);
2793 BUILD_ASSERT_DECL((int) OFPUTIL_C_TABLE_STATS == OFPC_TABLE_STATS);
2794 BUILD_ASSERT_DECL((int) OFPUTIL_C_PORT_STATS == OFPC_PORT_STATS);
2795 BUILD_ASSERT_DECL((int) OFPUTIL_C_IP_REASM == OFPC_IP_REASM);
2796 BUILD_ASSERT_DECL((int) OFPUTIL_C_QUEUE_STATS == OFPC_QUEUE_STATS);
2797 BUILD_ASSERT_DECL((int) OFPUTIL_C_ARP_MATCH_IP == OFPC_ARP_MATCH_IP);
2798
2799 struct ofputil_action_bit_translation {
2800     enum ofputil_action_bitmap ofputil_bit;
2801     int of_bit;
2802 };
2803
2804 static const struct ofputil_action_bit_translation of10_action_bits[] = {
2805     { OFPUTIL_A_OUTPUT,       OFPAT10_OUTPUT },
2806     { OFPUTIL_A_SET_VLAN_VID, OFPAT10_SET_VLAN_VID },
2807     { OFPUTIL_A_SET_VLAN_PCP, OFPAT10_SET_VLAN_PCP },
2808     { OFPUTIL_A_STRIP_VLAN,   OFPAT10_STRIP_VLAN },
2809     { OFPUTIL_A_SET_DL_SRC,   OFPAT10_SET_DL_SRC },
2810     { OFPUTIL_A_SET_DL_DST,   OFPAT10_SET_DL_DST },
2811     { OFPUTIL_A_SET_NW_SRC,   OFPAT10_SET_NW_SRC },
2812     { OFPUTIL_A_SET_NW_DST,   OFPAT10_SET_NW_DST },
2813     { OFPUTIL_A_SET_NW_TOS,   OFPAT10_SET_NW_TOS },
2814     { OFPUTIL_A_SET_TP_SRC,   OFPAT10_SET_TP_SRC },
2815     { OFPUTIL_A_SET_TP_DST,   OFPAT10_SET_TP_DST },
2816     { OFPUTIL_A_ENQUEUE,      OFPAT10_ENQUEUE },
2817     { 0, 0 },
2818 };
2819
2820 static const struct ofputil_action_bit_translation of11_action_bits[] = {
2821     { OFPUTIL_A_OUTPUT,         OFPAT11_OUTPUT },
2822     { OFPUTIL_A_SET_VLAN_VID,   OFPAT11_SET_VLAN_VID },
2823     { OFPUTIL_A_SET_VLAN_PCP,   OFPAT11_SET_VLAN_PCP },
2824     { OFPUTIL_A_SET_DL_SRC,     OFPAT11_SET_DL_SRC },
2825     { OFPUTIL_A_SET_DL_DST,     OFPAT11_SET_DL_DST },
2826     { OFPUTIL_A_SET_NW_SRC,     OFPAT11_SET_NW_SRC },
2827     { OFPUTIL_A_SET_NW_DST,     OFPAT11_SET_NW_DST },
2828     { OFPUTIL_A_SET_NW_TOS,     OFPAT11_SET_NW_TOS },
2829     { OFPUTIL_A_SET_NW_ECN,     OFPAT11_SET_NW_ECN },
2830     { OFPUTIL_A_SET_TP_SRC,     OFPAT11_SET_TP_SRC },
2831     { OFPUTIL_A_SET_TP_DST,     OFPAT11_SET_TP_DST },
2832     { OFPUTIL_A_COPY_TTL_OUT,   OFPAT11_COPY_TTL_OUT },
2833     { OFPUTIL_A_COPY_TTL_IN,    OFPAT11_COPY_TTL_IN },
2834     { OFPUTIL_A_SET_MPLS_LABEL, OFPAT11_SET_MPLS_LABEL },
2835     { OFPUTIL_A_SET_MPLS_TC,    OFPAT11_SET_MPLS_TC },
2836     { OFPUTIL_A_SET_MPLS_TTL,   OFPAT11_SET_MPLS_TTL },
2837     { OFPUTIL_A_DEC_MPLS_TTL,   OFPAT11_DEC_MPLS_TTL },
2838     { OFPUTIL_A_PUSH_VLAN,      OFPAT11_PUSH_VLAN },
2839     { OFPUTIL_A_POP_VLAN,       OFPAT11_POP_VLAN },
2840     { OFPUTIL_A_PUSH_MPLS,      OFPAT11_PUSH_MPLS },
2841     { OFPUTIL_A_POP_MPLS,       OFPAT11_POP_MPLS },
2842     { OFPUTIL_A_SET_QUEUE,      OFPAT11_SET_QUEUE },
2843     { OFPUTIL_A_GROUP,          OFPAT11_GROUP },
2844     { OFPUTIL_A_SET_NW_TTL,     OFPAT11_SET_NW_TTL },
2845     { OFPUTIL_A_DEC_NW_TTL,     OFPAT11_DEC_NW_TTL },
2846     { 0, 0 },
2847 };
2848
2849 static enum ofputil_action_bitmap
2850 decode_action_bits(ovs_be32 of_actions,
2851                    const struct ofputil_action_bit_translation *x)
2852 {
2853     enum ofputil_action_bitmap ofputil_actions;
2854
2855     ofputil_actions = 0;
2856     for (; x->ofputil_bit; x++) {
2857         if (of_actions & htonl(1u << x->of_bit)) {
2858             ofputil_actions |= x->ofputil_bit;
2859         }
2860     }
2861     return ofputil_actions;
2862 }
2863
2864 /* Decodes an OpenFlow 1.0 or 1.1 "switch_features" structure 'osf' into an
2865  * abstract representation in '*features'.  Initializes '*b' to iterate over
2866  * the OpenFlow port structures following 'osf' with later calls to
2867  * ofputil_pull_phy_port().  Returns 0 if successful, otherwise an
2868  * OFPERR_* value.  */
2869 enum ofperr
2870 ofputil_decode_switch_features(const struct ofp_switch_features *osf,
2871                                struct ofputil_switch_features *features,
2872                                struct ofpbuf *b)
2873 {
2874     ofpbuf_use_const(b, osf, ntohs(osf->header.length));
2875     ofpbuf_pull(b, sizeof *osf);
2876
2877     features->datapath_id = ntohll(osf->datapath_id);
2878     features->n_buffers = ntohl(osf->n_buffers);
2879     features->n_tables = osf->n_tables;
2880
2881     features->capabilities = ntohl(osf->capabilities) & OFPC_COMMON;
2882
2883     if (b->size % ofputil_get_phy_port_size(osf->header.version)) {
2884         return OFPERR_OFPBRC_BAD_LEN;
2885     }
2886
2887     if (osf->header.version == OFP10_VERSION) {
2888         if (osf->capabilities & htonl(OFPC10_STP)) {
2889             features->capabilities |= OFPUTIL_C_STP;
2890         }
2891         features->actions = decode_action_bits(osf->actions, of10_action_bits);
2892     } else if (osf->header.version == OFP11_VERSION) {
2893         if (osf->capabilities & htonl(OFPC11_GROUP_STATS)) {
2894             features->capabilities |= OFPUTIL_C_GROUP_STATS;
2895         }
2896         features->actions = decode_action_bits(osf->actions, of11_action_bits);
2897     } else {
2898         return OFPERR_OFPBRC_BAD_VERSION;
2899     }
2900
2901     return 0;
2902 }
2903
2904 /* Returns true if the maximum number of ports are in 'osf'. */
2905 static bool
2906 max_ports_in_features(const struct ofp_switch_features *osf)
2907 {
2908     size_t pp_size = ofputil_get_phy_port_size(osf->header.version);
2909     return ntohs(osf->header.length) + pp_size > UINT16_MAX;
2910 }
2911
2912 /* Given a buffer 'b' that contains a Features Reply message, checks if
2913  * it contains the maximum number of ports that will fit.  If so, it
2914  * returns true and removes the ports from the message.  The caller
2915  * should then send an OFPST_PORT_DESC stats request to get the ports,
2916  * since the switch may have more ports than could be represented in the
2917  * Features Reply.  Otherwise, returns false.
2918  */
2919 bool
2920 ofputil_switch_features_ports_trunc(struct ofpbuf *b)
2921 {
2922     struct ofp_switch_features *osf = b->data;
2923
2924     if (max_ports_in_features(osf)) {
2925         /* Remove all the ports. */
2926         b->size = sizeof(*osf);
2927         update_openflow_length(b);
2928
2929         return true;
2930     }
2931
2932     return false;
2933 }
2934
2935 static ovs_be32
2936 encode_action_bits(enum ofputil_action_bitmap ofputil_actions,
2937                    const struct ofputil_action_bit_translation *x)
2938 {
2939     uint32_t of_actions;
2940
2941     of_actions = 0;
2942     for (; x->ofputil_bit; x++) {
2943         if (ofputil_actions & x->ofputil_bit) {
2944             of_actions |= 1 << x->of_bit;
2945         }
2946     }
2947     return htonl(of_actions);
2948 }
2949
2950 /* Returns a buffer owned by the caller that encodes 'features' in the format
2951  * required by 'protocol' with the given 'xid'.  The caller should append port
2952  * information to the buffer with subsequent calls to
2953  * ofputil_put_switch_features_port(). */
2954 struct ofpbuf *
2955 ofputil_encode_switch_features(const struct ofputil_switch_features *features,
2956                                enum ofputil_protocol protocol, ovs_be32 xid)
2957 {
2958     struct ofp_switch_features *osf;
2959     struct ofpbuf *b;
2960
2961     osf = make_openflow_xid(sizeof *osf, OFPT_FEATURES_REPLY, xid, &b);
2962     osf->header.version = ofputil_protocol_to_ofp_version(protocol);
2963     osf->datapath_id = htonll(features->datapath_id);
2964     osf->n_buffers = htonl(features->n_buffers);
2965     osf->n_tables = features->n_tables;
2966
2967     osf->capabilities = htonl(features->capabilities & OFPC_COMMON);
2968     if (osf->header.version == OFP10_VERSION) {
2969         if (features->capabilities & OFPUTIL_C_STP) {
2970             osf->capabilities |= htonl(OFPC10_STP);
2971         }
2972         osf->actions = encode_action_bits(features->actions, of10_action_bits);
2973     } else {
2974         if (features->capabilities & OFPUTIL_C_GROUP_STATS) {
2975             osf->capabilities |= htonl(OFPC11_GROUP_STATS);
2976         }
2977         osf->actions = encode_action_bits(features->actions, of11_action_bits);
2978     }
2979
2980     return b;
2981 }
2982
2983 /* Encodes 'pp' into the format required by the switch_features message already
2984  * in 'b', which should have been returned by ofputil_encode_switch_features(),
2985  * and appends the encoded version to 'b'. */
2986 void
2987 ofputil_put_switch_features_port(const struct ofputil_phy_port *pp,
2988                                  struct ofpbuf *b)
2989 {
2990     const struct ofp_switch_features *osf = b->data;
2991
2992     ofputil_put_phy_port(osf->header.version, pp, b);
2993 }
2994 \f
2995 /* ofputil_port_status */
2996
2997 /* Decodes the OpenFlow "port status" message in '*ops' into an abstract form
2998  * in '*ps'.  Returns 0 if successful, otherwise an OFPERR_* value. */
2999 enum ofperr
3000 ofputil_decode_port_status(const struct ofp_port_status *ops,
3001                            struct ofputil_port_status *ps)
3002 {
3003     struct ofpbuf b;
3004     int retval;
3005
3006     if (ops->reason != OFPPR_ADD &&
3007         ops->reason != OFPPR_DELETE &&
3008         ops->reason != OFPPR_MODIFY) {
3009         return OFPERR_NXBRC_BAD_REASON;
3010     }
3011     ps->reason = ops->reason;
3012
3013     ofpbuf_use_const(&b, ops, ntohs(ops->header.length));
3014     ofpbuf_pull(&b, sizeof *ops);
3015     retval = ofputil_pull_phy_port(ops->header.version, &b, &ps->desc);
3016     assert(retval != EOF);
3017     return retval;
3018 }
3019
3020 /* Converts the abstract form of a "port status" message in '*ps' into an
3021  * OpenFlow message suitable for 'protocol', and returns that encoded form in
3022  * a buffer owned by the caller. */
3023 struct ofpbuf *
3024 ofputil_encode_port_status(const struct ofputil_port_status *ps,
3025                            enum ofputil_protocol protocol)
3026 {
3027     struct ofp_port_status *ops;
3028     struct ofpbuf *b;
3029
3030     b = ofpbuf_new(sizeof *ops + sizeof(struct ofp11_port));
3031     ops = put_openflow_xid(sizeof *ops, OFPT_PORT_STATUS, htonl(0), b);
3032     ops->header.version = ofputil_protocol_to_ofp_version(protocol);
3033     ops->reason = ps->reason;
3034     ofputil_put_phy_port(ops->header.version, &ps->desc, b);
3035     update_openflow_length(b);
3036     return b;
3037 }
3038 \f
3039 /* ofputil_port_mod */
3040
3041 /* Decodes the OpenFlow "port mod" message in '*oh' into an abstract form in
3042  * '*pm'.  Returns 0 if successful, otherwise an OFPERR_* value. */
3043 enum ofperr
3044 ofputil_decode_port_mod(const struct ofp_header *oh,
3045                         struct ofputil_port_mod *pm)
3046 {
3047     if (oh->version == OFP10_VERSION) {
3048         const struct ofp10_port_mod *opm = (const struct ofp10_port_mod *) oh;
3049
3050         if (oh->length != htons(sizeof *opm)) {
3051             return OFPERR_OFPBRC_BAD_LEN;
3052         }
3053
3054         pm->port_no = ntohs(opm->port_no);
3055         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
3056         pm->config = ntohl(opm->config) & OFPPC10_ALL;
3057         pm->mask = ntohl(opm->mask) & OFPPC10_ALL;
3058         pm->advertise = netdev_port_features_from_ofp10(opm->advertise);
3059     } else if (oh->version == OFP11_VERSION) {
3060         const struct ofp11_port_mod *opm = (const struct ofp11_port_mod *) oh;
3061         enum ofperr error;
3062
3063         if (oh->length != htons(sizeof *opm)) {
3064             return OFPERR_OFPBRC_BAD_LEN;
3065         }
3066
3067         error = ofputil_port_from_ofp11(opm->port_no, &pm->port_no);
3068         if (error) {
3069             return error;
3070         }
3071
3072         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
3073         pm->config = ntohl(opm->config) & OFPPC11_ALL;
3074         pm->mask = ntohl(opm->mask) & OFPPC11_ALL;
3075         pm->advertise = netdev_port_features_from_ofp11(opm->advertise);
3076     } else {
3077         return OFPERR_OFPBRC_BAD_VERSION;
3078     }
3079
3080     pm->config &= pm->mask;
3081     return 0;
3082 }
3083
3084 /* Converts the abstract form of a "port mod" message in '*pm' into an OpenFlow
3085  * message suitable for 'protocol', and returns that encoded form in a buffer
3086  * owned by the caller. */
3087 struct ofpbuf *
3088 ofputil_encode_port_mod(const struct ofputil_port_mod *pm,
3089                         enum ofputil_protocol protocol)
3090 {
3091     uint8_t ofp_version = ofputil_protocol_to_ofp_version(protocol);
3092     struct ofpbuf *b;
3093
3094     if (ofp_version == OFP10_VERSION) {
3095         struct ofp10_port_mod *opm;
3096
3097         opm = make_openflow(sizeof *opm, OFPT10_PORT_MOD, &b);
3098         opm->port_no = htons(pm->port_no);
3099         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
3100         opm->config = htonl(pm->config & OFPPC10_ALL);
3101         opm->mask = htonl(pm->mask & OFPPC10_ALL);
3102         opm->advertise = netdev_port_features_to_ofp10(pm->advertise);
3103     } else if (ofp_version == OFP11_VERSION) {
3104         struct ofp11_port_mod *opm;
3105
3106         opm = make_openflow(sizeof *opm, OFPT11_PORT_MOD, &b);
3107         opm->port_no = htonl(pm->port_no);
3108         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
3109         opm->config = htonl(pm->config & OFPPC11_ALL);
3110         opm->mask = htonl(pm->mask & OFPPC11_ALL);
3111         opm->advertise = netdev_port_features_to_ofp11(pm->advertise);
3112     } else {
3113         NOT_REACHED();
3114     }
3115
3116     return b;
3117 }
3118 \f
3119 /* ofputil_flow_monitor_request */
3120
3121 /* Converts an NXST_FLOW_MONITOR request in 'msg' into an abstract
3122  * ofputil_flow_monitor_request in 'rq'.
3123  *
3124  * Multiple NXST_FLOW_MONITOR requests can be packed into a single OpenFlow
3125  * message.  Calling this function multiple times for a single 'msg' iterates
3126  * through the requests.  The caller must initially leave 'msg''s layer
3127  * pointers null and not modify them between calls.
3128  *
3129  * Returns 0 if successful, EOF if no requests were left in this 'msg',
3130  * otherwise an OFPERR_* value. */
3131 int
3132 ofputil_decode_flow_monitor_request(struct ofputil_flow_monitor_request *rq,
3133                                     struct ofpbuf *msg)
3134 {
3135     struct nx_flow_monitor_request *nfmr;
3136     uint16_t flags;
3137
3138     if (!msg->l2) {
3139         msg->l2 = msg->data;
3140         ofpbuf_pull(msg, sizeof(struct nicira_stats_msg));
3141     }
3142
3143     if (!msg->size) {
3144         return EOF;
3145     }
3146
3147     nfmr = ofpbuf_try_pull(msg, sizeof *nfmr);
3148     if (!nfmr) {
3149         VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR request has %zu "
3150                      "leftover bytes at end", msg->size);
3151         return OFPERR_OFPBRC_BAD_LEN;
3152     }
3153
3154     flags = ntohs(nfmr->flags);
3155     if (!(flags & (NXFMF_ADD | NXFMF_DELETE | NXFMF_MODIFY))
3156         || flags & ~(NXFMF_INITIAL | NXFMF_ADD | NXFMF_DELETE
3157                      | NXFMF_MODIFY | NXFMF_ACTIONS | NXFMF_OWN)) {
3158         VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR has bad flags %#"PRIx16,
3159                      flags);
3160         return OFPERR_NXBRC_FM_BAD_FLAGS;
3161     }
3162
3163     if (!is_all_zeros(nfmr->zeros, sizeof nfmr->zeros)) {
3164         return OFPERR_NXBRC_MUST_BE_ZERO;
3165     }
3166
3167     rq->id = ntohl(nfmr->id);
3168     rq->flags = flags;
3169     rq->out_port = ntohs(nfmr->out_port);
3170     rq->table_id = nfmr->table_id;
3171
3172     return nx_pull_match(msg, ntohs(nfmr->match_len), OFP_DEFAULT_PRIORITY,
3173                          &rq->match, NULL, NULL);
3174 }
3175
3176 void
3177 ofputil_append_flow_monitor_request(
3178     const struct ofputil_flow_monitor_request *rq, struct ofpbuf *msg)
3179 {
3180     struct nx_flow_monitor_request *nfmr;
3181     size_t start_ofs;
3182     int match_len;
3183
3184     if (!msg->size) {
3185         ofputil_put_stats_header(alloc_xid(), OFPT10_STATS_REQUEST,
3186                                  htons(OFPST_VENDOR),
3187                                  htonl(NXST_FLOW_MONITOR), msg);
3188     }
3189
3190     start_ofs = msg->size;
3191     ofpbuf_put_zeros(msg, sizeof *nfmr);
3192     match_len = nx_put_match(msg, false, &rq->match, htonll(0), htonll(0));
3193
3194     nfmr = ofpbuf_at_assert(msg, start_ofs, sizeof *nfmr);
3195     nfmr->id = htonl(rq->id);
3196     nfmr->flags = htons(rq->flags);
3197     nfmr->out_port = htons(rq->out_port);
3198     nfmr->match_len = htons(match_len);
3199     nfmr->table_id = rq->table_id;
3200 }
3201
3202 /* Converts an NXST_FLOW_MONITOR reply (also known as a flow update) in 'msg'
3203  * into an abstract ofputil_flow_update in 'update'.  The caller must have
3204  * initialized update->match to point to space allocated for a cls_rule.
3205  *
3206  * Uses 'ofpacts' to store the abstract OFPACT_* version of the update's
3207  * actions (except for NXFME_ABBREV, which never includes actions).  The caller
3208  * must initialize 'ofpacts' and retains ownership of it.  'update->ofpacts'
3209  * will point into the 'ofpacts' buffer.
3210  *
3211  * Multiple flow updates can be packed into a single OpenFlow message.  Calling
3212  * this function multiple times for a single 'msg' iterates through the
3213  * updates.  The caller must initially leave 'msg''s layer pointers null and
3214  * not modify them between calls.
3215  *
3216  * Returns 0 if successful, EOF if no updates were left in this 'msg',
3217  * otherwise an OFPERR_* value. */
3218 int
3219 ofputil_decode_flow_update(struct ofputil_flow_update *update,
3220                            struct ofpbuf *msg, struct ofpbuf *ofpacts)
3221 {
3222     struct nx_flow_update_header *nfuh;
3223     unsigned int length;
3224
3225     if (!msg->l2) {
3226         msg->l2 = msg->data;
3227         ofpbuf_pull(msg, sizeof(struct nicira_stats_msg));
3228     }
3229
3230     if (!msg->size) {
3231         return EOF;
3232     }
3233
3234     if (msg->size < sizeof(struct nx_flow_update_header)) {
3235         goto bad_len;
3236     }
3237
3238     nfuh = msg->data;
3239     update->event = ntohs(nfuh->event);
3240     length = ntohs(nfuh->length);
3241     if (length > msg->size || length % 8) {
3242         goto bad_len;
3243     }
3244
3245     if (update->event == NXFME_ABBREV) {
3246         struct nx_flow_update_abbrev *nfua;
3247
3248         if (length != sizeof *nfua) {
3249             goto bad_len;
3250         }
3251
3252         nfua = ofpbuf_pull(msg, sizeof *nfua);
3253         update->xid = nfua->xid;
3254         return 0;
3255     } else if (update->event == NXFME_ADDED
3256                || update->event == NXFME_DELETED
3257                || update->event == NXFME_MODIFIED) {
3258         struct nx_flow_update_full *nfuf;
3259         unsigned int actions_len;
3260         unsigned int match_len;
3261         enum ofperr error;
3262
3263         if (length < sizeof *nfuf) {
3264             goto bad_len;
3265         }
3266
3267         nfuf = ofpbuf_pull(msg, sizeof *nfuf);
3268         match_len = ntohs(nfuf->match_len);
3269         if (sizeof *nfuf + match_len > length) {
3270             goto bad_len;
3271         }
3272
3273         update->reason = ntohs(nfuf->reason);
3274         update->idle_timeout = ntohs(nfuf->idle_timeout);
3275         update->hard_timeout = ntohs(nfuf->hard_timeout);
3276         update->table_id = nfuf->table_id;
3277         update->cookie = nfuf->cookie;
3278
3279         error = nx_pull_match(msg, match_len, ntohs(nfuf->priority),
3280                               update->match, NULL, NULL);
3281         if (error) {
3282             return error;
3283         }
3284
3285         actions_len = length - sizeof *nfuf - ROUND_UP(match_len, 8);
3286         error = ofpacts_pull_openflow10(msg, actions_len, ofpacts);
3287         if (error) {
3288             return error;
3289         }
3290
3291         update->ofpacts = ofpacts->data;
3292         update->ofpacts_len = ofpacts->size;
3293         return 0;
3294     } else {
3295         VLOG_WARN_RL(&bad_ofmsg_rl,
3296                      "NXST_FLOW_MONITOR reply has bad event %"PRIu16,
3297                      ntohs(nfuh->event));
3298         return OFPERR_OFPET_BAD_REQUEST;
3299     }
3300
3301 bad_len:
3302     VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR reply has %zu "
3303                  "leftover bytes at end", msg->size);
3304     return OFPERR_OFPBRC_BAD_LEN;
3305 }
3306
3307 uint32_t
3308 ofputil_decode_flow_monitor_cancel(const struct ofp_header *oh)
3309 {
3310     return ntohl(((const struct nx_flow_monitor_cancel *) oh)->id);
3311 }
3312
3313 struct ofpbuf *
3314 ofputil_encode_flow_monitor_cancel(uint32_t id)
3315 {
3316     struct nx_flow_monitor_cancel *nfmc;
3317     struct ofpbuf *msg;
3318
3319     nfmc = make_nxmsg(sizeof *nfmc, NXT_FLOW_MONITOR_CANCEL, &msg);
3320     nfmc->id = htonl(id);
3321     return msg;
3322 }
3323
3324 void
3325 ofputil_start_flow_update(struct list *replies)
3326 {
3327     struct ofpbuf *msg;
3328
3329     msg = ofpbuf_new(1024);
3330     ofputil_put_stats_header(htonl(0), OFPT10_STATS_REPLY,
3331                              htons(OFPST_VENDOR),
3332                              htonl(NXST_FLOW_MONITOR), msg);
3333
3334     list_init(replies);
3335     list_push_back(replies, &msg->list_node);
3336 }
3337
3338 void
3339 ofputil_append_flow_update(const struct ofputil_flow_update *update,
3340                            struct list *replies)
3341 {
3342     struct nx_flow_update_header *nfuh;
3343     struct ofpbuf *msg;
3344     size_t start_ofs;
3345
3346     msg = ofpbuf_from_list(list_back(replies));
3347     start_ofs = msg->size;
3348
3349     if (update->event == NXFME_ABBREV) {
3350         struct nx_flow_update_abbrev *nfua;
3351
3352         nfua = ofpbuf_put_zeros(msg, sizeof *nfua);
3353         nfua->xid = update->xid;
3354     } else {
3355         struct nx_flow_update_full *nfuf;
3356         int match_len;
3357
3358         ofpbuf_put_zeros(msg, sizeof *nfuf);
3359         match_len = nx_put_match(msg, false, update->match,
3360                                  htonll(0), htonll(0));
3361         ofpacts_put_openflow10(update->ofpacts, update->ofpacts_len, msg);
3362
3363         nfuf = ofpbuf_at_assert(msg, start_ofs, sizeof *nfuf);
3364         nfuf->reason = htons(update->reason);
3365         nfuf->priority = htons(update->match->priority);
3366         nfuf->idle_timeout = htons(update->idle_timeout);
3367         nfuf->hard_timeout = htons(update->hard_timeout);
3368         nfuf->match_len = htons(match_len);
3369         nfuf->table_id = update->table_id;
3370         nfuf->cookie = update->cookie;
3371     }
3372
3373     nfuh = ofpbuf_at_assert(msg, start_ofs, sizeof *nfuh);
3374     nfuh->length = htons(msg->size - start_ofs);
3375     nfuh->event = htons(update->event);
3376
3377     ofputil_postappend_stats_reply(start_ofs, replies);
3378 }
3379 \f
3380 struct ofpbuf *
3381 ofputil_encode_packet_out(const struct ofputil_packet_out *po)
3382 {
3383     struct ofp_packet_out *opo;
3384     struct ofpbuf *msg;
3385     size_t size;
3386
3387     size = sizeof *opo + po->ofpacts_len;
3388     if (po->buffer_id == UINT32_MAX) {
3389         size += po->packet_len;
3390     }
3391
3392     msg = ofpbuf_new(size);
3393     put_openflow(sizeof *opo, OFPT_PACKET_OUT, msg);
3394     ofpacts_put_openflow10(po->ofpacts, po->ofpacts_len, msg);
3395
3396     opo = msg->data;
3397     opo->buffer_id = htonl(po->buffer_id);
3398     opo->in_port = htons(po->in_port);
3399     opo->actions_len = htons(msg->size - sizeof *opo);
3400
3401     if (po->buffer_id == UINT32_MAX) {
3402         ofpbuf_put(msg, po->packet, po->packet_len);
3403     }
3404
3405     update_openflow_length(msg);
3406
3407     return msg;
3408 }
3409
3410 /* Returns a string representing the message type of 'type'.  The string is the
3411  * enumeration constant for the type, e.g. "OFPT_HELLO".  For statistics
3412  * messages, the constant is followed by "request" or "reply",
3413  * e.g. "OFPST_AGGREGATE reply". */
3414 const char *
3415 ofputil_msg_type_name(const struct ofputil_msg_type *type)
3416 {
3417     return type->name;
3418 }
3419 \f
3420 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
3421  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
3422  * an arbitrary transaction id.  Allocated bytes beyond the header, if any, are
3423  * zeroed.
3424  *
3425  * The caller is responsible for freeing '*bufferp' when it is no longer
3426  * needed.
3427  *
3428  * The OpenFlow header length is initially set to 'openflow_len'; if the
3429  * message is later extended, the length should be updated with
3430  * update_openflow_length() before sending.
3431  *
3432  * Returns the header. */
3433 void *
3434 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp)
3435 {
3436     *bufferp = ofpbuf_new(openflow_len);
3437     return put_openflow_xid(openflow_len, type, alloc_xid(), *bufferp);
3438 }
3439
3440 /* Similar to make_openflow() but creates a Nicira vendor extension message
3441  * with the specific 'subtype'.  'subtype' should be in host byte order. */
3442 void *
3443 make_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf **bufferp)
3444 {
3445     return make_nxmsg_xid(openflow_len, subtype, alloc_xid(), bufferp);
3446 }
3447
3448 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
3449  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
3450  * transaction id 'xid'.  Allocated bytes beyond the header, if any, are
3451  * zeroed.
3452  *
3453  * The caller is responsible for freeing '*bufferp' when it is no longer
3454  * needed.
3455  *
3456  * The OpenFlow header length is initially set to 'openflow_len'; if the
3457  * message is later extended, the length should be updated with
3458  * update_openflow_length() before sending.
3459  *
3460  * Returns the header. */
3461 void *
3462 make_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
3463                   struct ofpbuf **bufferp)
3464 {
3465     *bufferp = ofpbuf_new(openflow_len);
3466     return put_openflow_xid(openflow_len, type, xid, *bufferp);
3467 }
3468
3469 /* Similar to make_openflow_xid() but creates a Nicira vendor extension message
3470  * with the specific 'subtype'.  'subtype' should be in host byte order. */
3471 void *
3472 make_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
3473                struct ofpbuf **bufferp)
3474 {
3475     *bufferp = ofpbuf_new(openflow_len);
3476     return put_nxmsg_xid(openflow_len, subtype, xid, *bufferp);
3477 }
3478
3479 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
3480  * with the given 'type' and an arbitrary transaction id.  Allocated bytes
3481  * beyond the header, if any, are zeroed.
3482  *
3483  * The OpenFlow header length is initially set to 'openflow_len'; if the
3484  * message is later extended, the length should be updated with
3485  * update_openflow_length() before sending.
3486  *
3487  * Returns the header. */
3488 void *
3489 put_openflow(size_t openflow_len, uint8_t type, struct ofpbuf *buffer)
3490 {
3491     return put_openflow_xid(openflow_len, type, alloc_xid(), buffer);
3492 }
3493
3494 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
3495  * with the given 'type' and an transaction id 'xid'.  Allocated bytes beyond
3496  * the header, if any, are zeroed.
3497  *
3498  * The OpenFlow header length is initially set to 'openflow_len'; if the
3499  * message is later extended, the length should be updated with
3500  * update_openflow_length() before sending.
3501  *
3502  * Returns the header. */
3503 void *
3504 put_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
3505                  struct ofpbuf *buffer)
3506 {
3507     struct ofp_header *oh;
3508
3509     assert(openflow_len >= sizeof *oh);
3510     assert(openflow_len <= UINT16_MAX);
3511
3512     oh = ofpbuf_put_uninit(buffer, openflow_len);
3513     oh->version = OFP10_VERSION;
3514     oh->type = type;
3515     oh->length = htons(openflow_len);
3516     oh->xid = xid;
3517     memset(oh + 1, 0, openflow_len - sizeof *oh);
3518     return oh;
3519 }
3520
3521 /* Similar to put_openflow() but append a Nicira vendor extension message with
3522  * the specific 'subtype'.  'subtype' should be in host byte order. */
3523 void *
3524 put_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf *buffer)
3525 {
3526     return put_nxmsg_xid(openflow_len, subtype, alloc_xid(), buffer);
3527 }
3528
3529 /* Similar to put_openflow_xid() but append a Nicira vendor extension message
3530  * with the specific 'subtype'.  'subtype' should be in host byte order. */
3531 void *
3532 put_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
3533               struct ofpbuf *buffer)
3534 {
3535     struct nicira_header *nxh;
3536
3537     nxh = put_openflow_xid(openflow_len, OFPT_VENDOR, xid, buffer);
3538     nxh->vendor = htonl(NX_VENDOR_ID);
3539     nxh->subtype = htonl(subtype);
3540     return nxh;
3541 }
3542
3543 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
3544  * 'buffer->size'. */
3545 void
3546 update_openflow_length(struct ofpbuf *buffer)
3547 {
3548     struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
3549     oh->length = htons(buffer->size);
3550 }
3551
3552 void
3553 ofputil_put_stats_header(ovs_be32 xid, uint8_t ofp_type,
3554                          ovs_be16 ofpst_type, ovs_be32 nxst_subtype,
3555                          struct ofpbuf *msg)
3556 {
3557     if (ofpst_type == htons(OFPST_VENDOR)) {
3558         struct nicira_stats_msg *nsm;
3559
3560         nsm = put_openflow_xid(sizeof *nsm, ofp_type, xid, msg);
3561         nsm->vsm.osm.type = ofpst_type;
3562         nsm->vsm.vendor = htonl(NX_VENDOR_ID);
3563         nsm->subtype = nxst_subtype;
3564     } else {
3565         struct ofp_stats_msg *osm;
3566
3567         osm = put_openflow_xid(sizeof *osm, ofp_type, xid, msg);
3568         osm->type = ofpst_type;
3569     }
3570 }
3571
3572 /* Creates a statistics request message with total length 'openflow_len'
3573  * (including all headers) and the given 'ofpst_type', and stores the buffer
3574  * containing the new message in '*bufferp'.  If 'ofpst_type' is OFPST_VENDOR
3575  * then 'nxst_subtype' is used as the Nicira vendor extension statistics
3576  * subtype (otherwise 'nxst_subtype' is ignored).
3577  *
3578  * Initializes bytes following the headers to all-bits-zero.
3579  *
3580  * Returns the first byte of the new message. */
3581 void *
3582 ofputil_make_stats_request(size_t openflow_len, uint16_t ofpst_type,
3583                            uint32_t nxst_subtype, struct ofpbuf **bufferp)
3584 {
3585     struct ofpbuf *msg;
3586
3587     msg = *bufferp = ofpbuf_new(openflow_len);
3588     ofputil_put_stats_header(alloc_xid(), OFPT10_STATS_REQUEST,
3589                              htons(ofpst_type), htonl(nxst_subtype), msg);
3590     ofpbuf_padto(msg, openflow_len);
3591
3592     return msg->data;
3593 }
3594
3595 static void
3596 put_stats_reply__(const struct ofp_stats_msg *request, struct ofpbuf *msg)
3597 {
3598     ovs_be32 nxst_subtype;
3599
3600     assert(request->header.type == OFPT10_STATS_REQUEST ||
3601            request->header.type == OFPT10_STATS_REPLY);
3602
3603     nxst_subtype = (request->type != htons(OFPST_VENDOR)
3604                     ? htonl(0)
3605                     : ((const struct nicira_stats_msg *) request)->subtype);
3606     ofputil_put_stats_header(request->header.xid, OFPT10_STATS_REPLY,
3607                              request->type, nxst_subtype, msg);
3608 }
3609
3610 /* Creates a statistics reply message with total length 'openflow_len'
3611  * (including all headers) and the same type (either a standard OpenFlow
3612  * statistics type or a Nicira extension type and subtype) as 'request', and
3613  * stores the buffer containing the new message in '*bufferp'.
3614  *
3615  * Initializes bytes following the headers to all-bits-zero.
3616  *
3617  * Returns the first byte of the new message. */
3618 void *
3619 ofputil_make_stats_reply(size_t openflow_len,
3620                          const struct ofp_stats_msg *request,
3621                          struct ofpbuf **bufferp)
3622 {
3623     struct ofpbuf *msg;
3624
3625     msg = *bufferp = ofpbuf_new(openflow_len);
3626     put_stats_reply__(request, msg);
3627     ofpbuf_padto(msg, openflow_len);
3628
3629     return msg->data;
3630 }
3631
3632 /* Initializes 'replies' as a list of ofpbufs that will contain a series of
3633  * replies to 'request', which should be an OpenFlow or Nicira extension
3634  * statistics request.  Initially 'replies' will have a single reply message
3635  * that has only a header.  The functions ofputil_reserve_stats_reply() and
3636  * ofputil_append_stats_reply() may be used to add to the reply. */
3637 void
3638 ofputil_start_stats_reply(const struct ofp_stats_msg *request,
3639                           struct list *replies)
3640 {
3641     struct ofpbuf *msg;
3642
3643     msg = ofpbuf_new(1024);
3644     put_stats_reply__(request, msg);
3645
3646     list_init(replies);
3647     list_push_back(replies, &msg->list_node);
3648 }
3649
3650 /* Prepares to append up to 'len' bytes to the series of statistics replies in
3651  * 'replies', which should have been initialized with
3652  * ofputil_start_stats_reply().  Returns an ofpbuf with at least 'len' bytes of
3653  * tailroom.  (The 'len' bytes have not actually be allocated; the caller must
3654  * do so with e.g. ofpbuf_put_uninit().) */
3655 struct ofpbuf *
3656 ofputil_reserve_stats_reply(size_t len, struct list *replies)
3657 {
3658     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
3659     struct ofp_stats_msg *osm = msg->data;
3660
3661     if (msg->size + len <= UINT16_MAX) {
3662         ofpbuf_prealloc_tailroom(msg, len);
3663     } else {
3664         osm->flags |= htons(OFPSF_REPLY_MORE);
3665
3666         msg = ofpbuf_new(MAX(1024, sizeof(struct nicira_stats_msg) + len));
3667         put_stats_reply__(osm, msg);
3668         list_push_back(replies, &msg->list_node);
3669     }
3670     return msg;
3671 }
3672
3673 /* Appends 'len' bytes to the series of statistics replies in 'replies', and
3674  * returns the first byte. */
3675 void *
3676 ofputil_append_stats_reply(size_t len, struct list *replies)
3677 {
3678     return ofpbuf_put_uninit(ofputil_reserve_stats_reply(len, replies), len);
3679 }
3680
3681 /* Sometimes, when composing stats replies, it's difficult to predict how long
3682  * an individual reply chunk will be before actually encoding it into the reply
3683  * buffer.  This function allows easy handling of this case: just encode the
3684  * reply, then use this function to break the message into two pieces if it
3685  * exceeds the OpenFlow message limit.
3686  *
3687  * In detail, if the final stats message in 'replies' is too long for OpenFlow,
3688  * this function breaks it into two separate stats replies, the first one with
3689  * the first 'start_ofs' bytes, the second one containing the bytes from that
3690  * offset onward. */
3691 void
3692 ofputil_postappend_stats_reply(size_t start_ofs, struct list *replies)
3693 {
3694     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
3695
3696     assert(start_ofs <= UINT16_MAX);
3697     if (msg->size > UINT16_MAX) {
3698         size_t len = msg->size - start_ofs;
3699         memcpy(ofputil_append_stats_reply(len, replies),
3700                (const uint8_t *) msg->data + start_ofs, len);
3701         msg->size = start_ofs;
3702     }
3703 }
3704
3705 /* Returns the first byte past the ofp_stats_msg header in 'oh'. */
3706 const void *
3707 ofputil_stats_body(const struct ofp_header *oh)
3708 {
3709     assert(oh->type == OFPT10_STATS_REQUEST || oh->type == OFPT10_STATS_REPLY);
3710     return (const struct ofp_stats_msg *) oh + 1;
3711 }
3712
3713 /* Returns the number of bytes past the ofp_stats_msg header in 'oh'. */
3714 size_t
3715 ofputil_stats_body_len(const struct ofp_header *oh)
3716 {
3717     assert(oh->type == OFPT10_STATS_REQUEST || oh->type == OFPT10_STATS_REPLY);
3718     return ntohs(oh->length) - sizeof(struct ofp_stats_msg);
3719 }
3720
3721 /* Returns the first byte past the nicira_stats_msg header in 'oh'. */
3722 const void *
3723 ofputil_nxstats_body(const struct ofp_header *oh)
3724 {
3725     assert(oh->type == OFPT10_STATS_REQUEST || oh->type == OFPT10_STATS_REPLY);
3726     return ((const struct nicira_stats_msg *) oh) + 1;
3727 }
3728
3729 /* Returns the number of bytes past the nicira_stats_msg header in 'oh'. */
3730 size_t
3731 ofputil_nxstats_body_len(const struct ofp_header *oh)
3732 {
3733     assert(oh->type == OFPT10_STATS_REQUEST || oh->type == OFPT10_STATS_REPLY);
3734     return ntohs(oh->length) - sizeof(struct nicira_stats_msg);
3735 }
3736
3737 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
3738 struct ofpbuf *
3739 make_echo_request(void)
3740 {
3741     struct ofp_header *rq;
3742     struct ofpbuf *out = ofpbuf_new(sizeof *rq);
3743     rq = ofpbuf_put_uninit(out, sizeof *rq);
3744     rq->version = OFP10_VERSION;
3745     rq->type = OFPT_ECHO_REQUEST;
3746     rq->length = htons(sizeof *rq);
3747     rq->xid = htonl(0);
3748     return out;
3749 }
3750
3751 /* Creates and returns an OFPT_ECHO_REPLY message matching the
3752  * OFPT_ECHO_REQUEST message in 'rq'. */
3753 struct ofpbuf *
3754 make_echo_reply(const struct ofp_header *rq)
3755 {
3756     size_t size = ntohs(rq->length);
3757     struct ofpbuf *out = ofpbuf_new(size);
3758     struct ofp_header *reply = ofpbuf_put(out, rq, size);
3759     reply->type = OFPT_ECHO_REPLY;
3760     return out;
3761 }
3762
3763 struct ofpbuf *
3764 ofputil_encode_barrier_request(void)
3765 {
3766     struct ofpbuf *msg;
3767
3768     make_openflow(sizeof(struct ofp_header), OFPT10_BARRIER_REQUEST, &msg);
3769     return msg;
3770 }
3771
3772 const char *
3773 ofputil_frag_handling_to_string(enum ofp_config_flags flags)
3774 {
3775     switch (flags & OFPC_FRAG_MASK) {
3776     case OFPC_FRAG_NORMAL:   return "normal";
3777     case OFPC_FRAG_DROP:     return "drop";
3778     case OFPC_FRAG_REASM:    return "reassemble";
3779     case OFPC_FRAG_NX_MATCH: return "nx-match";
3780     }
3781
3782     NOT_REACHED();
3783 }
3784
3785 bool
3786 ofputil_frag_handling_from_string(const char *s, enum ofp_config_flags *flags)
3787 {
3788     if (!strcasecmp(s, "normal")) {
3789         *flags = OFPC_FRAG_NORMAL;
3790     } else if (!strcasecmp(s, "drop")) {
3791         *flags = OFPC_FRAG_DROP;
3792     } else if (!strcasecmp(s, "reassemble")) {
3793         *flags = OFPC_FRAG_REASM;
3794     } else if (!strcasecmp(s, "nx-match")) {
3795         *flags = OFPC_FRAG_NX_MATCH;
3796     } else {
3797         return false;
3798     }
3799     return true;
3800 }
3801
3802 /* Converts the OpenFlow 1.1+ port number 'ofp11_port' into an OpenFlow 1.0
3803  * port number and stores the latter in '*ofp10_port', for the purpose of
3804  * decoding OpenFlow 1.1+ protocol messages.  Returns 0 if successful,
3805  * otherwise an OFPERR_* number.
3806  *
3807  * See the definition of OFP11_MAX for an explanation of the mapping. */
3808 enum ofperr
3809 ofputil_port_from_ofp11(ovs_be32 ofp11_port, uint16_t *ofp10_port)
3810 {
3811     uint32_t ofp11_port_h = ntohl(ofp11_port);
3812
3813     if (ofp11_port_h < OFPP_MAX) {
3814         *ofp10_port = ofp11_port_h;
3815         return 0;
3816     } else if (ofp11_port_h >= OFPP11_MAX) {
3817         *ofp10_port = ofp11_port_h - OFPP11_OFFSET;
3818         return 0;
3819     } else {
3820         VLOG_WARN_RL(&bad_ofmsg_rl, "port %"PRIu32" is outside the supported "
3821                      "range 0 through %d or 0x%"PRIx32" through 0x%"PRIx32,
3822                      ofp11_port_h, OFPP_MAX - 1,
3823                      (uint32_t) OFPP11_MAX, UINT32_MAX);
3824         return OFPERR_OFPBAC_BAD_OUT_PORT;
3825     }
3826 }
3827
3828 /* Returns the OpenFlow 1.1+ port number equivalent to the OpenFlow 1.0 port
3829  * number 'ofp10_port', for encoding OpenFlow 1.1+ protocol messages.
3830  *
3831  * See the definition of OFP11_MAX for an explanation of the mapping. */
3832 ovs_be32
3833 ofputil_port_to_ofp11(uint16_t ofp10_port)
3834 {
3835     return htonl(ofp10_port < OFPP_MAX
3836                  ? ofp10_port
3837                  : ofp10_port + OFPP11_OFFSET);
3838 }
3839
3840 /* Checks that 'port' is a valid output port for the OFPAT10_OUTPUT action, given
3841  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
3842  * 'port' is valid, otherwise an OpenFlow return code. */
3843 enum ofperr
3844 ofputil_check_output_port(uint16_t port, int max_ports)
3845 {
3846     switch (port) {
3847     case OFPP_IN_PORT:
3848     case OFPP_TABLE:
3849     case OFPP_NORMAL:
3850     case OFPP_FLOOD:
3851     case OFPP_ALL:
3852     case OFPP_CONTROLLER:
3853     case OFPP_NONE:
3854     case OFPP_LOCAL:
3855         return 0;
3856
3857     default:
3858         if (port < max_ports) {
3859             return 0;
3860         }
3861         return OFPERR_OFPBAC_BAD_OUT_PORT;
3862     }
3863 }
3864
3865 #define OFPUTIL_NAMED_PORTS                     \
3866         OFPUTIL_NAMED_PORT(IN_PORT)             \
3867         OFPUTIL_NAMED_PORT(TABLE)               \
3868         OFPUTIL_NAMED_PORT(NORMAL)              \
3869         OFPUTIL_NAMED_PORT(FLOOD)               \
3870         OFPUTIL_NAMED_PORT(ALL)                 \
3871         OFPUTIL_NAMED_PORT(CONTROLLER)          \
3872         OFPUTIL_NAMED_PORT(LOCAL)               \
3873         OFPUTIL_NAMED_PORT(NONE)
3874
3875 /* Checks whether 's' is the string representation of an OpenFlow port number,
3876  * either as an integer or a string name (e.g. "LOCAL").  If it is, stores the
3877  * number in '*port' and returns true.  Otherwise, returns false. */
3878 bool
3879 ofputil_port_from_string(const char *name, uint16_t *port)
3880 {
3881     struct pair {
3882         const char *name;
3883         uint16_t value;
3884     };
3885     static const struct pair pairs[] = {
3886 #define OFPUTIL_NAMED_PORT(NAME) {#NAME, OFPP_##NAME},
3887         OFPUTIL_NAMED_PORTS
3888 #undef OFPUTIL_NAMED_PORT
3889     };
3890     static const int n_pairs = ARRAY_SIZE(pairs);
3891     int i;
3892
3893     if (str_to_int(name, 0, &i) && i >= 0 && i < UINT16_MAX) {
3894         *port = i;
3895         return true;
3896     }
3897
3898     for (i = 0; i < n_pairs; i++) {
3899         if (!strcasecmp(name, pairs[i].name)) {
3900             *port = pairs[i].value;
3901             return true;
3902         }
3903     }
3904     return false;
3905 }
3906
3907 /* Appends to 's' a string representation of the OpenFlow port number 'port'.
3908  * Most ports' string representation is just the port number, but for special
3909  * ports, e.g. OFPP_LOCAL, it is the name, e.g. "LOCAL". */
3910 void
3911 ofputil_format_port(uint16_t port, struct ds *s)
3912 {
3913     const char *name;
3914
3915     switch (port) {
3916 #define OFPUTIL_NAMED_PORT(NAME) case OFPP_##NAME: name = #NAME; break;
3917         OFPUTIL_NAMED_PORTS
3918 #undef OFPUTIL_NAMED_PORT
3919
3920     default:
3921         ds_put_format(s, "%"PRIu16, port);
3922         return;
3923     }
3924     ds_put_cstr(s, name);
3925 }
3926
3927 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
3928  * 'ofp_version', tries to pull the first element from the array.  If
3929  * successful, initializes '*pp' with an abstract representation of the
3930  * port and returns 0.  If no ports remain to be decoded, returns EOF.
3931  * On an error, returns a positive OFPERR_* value. */
3932 int
3933 ofputil_pull_phy_port(uint8_t ofp_version, struct ofpbuf *b,
3934                       struct ofputil_phy_port *pp)
3935 {
3936     if (ofp_version == OFP10_VERSION) {
3937         const struct ofp10_phy_port *opp = ofpbuf_try_pull(b, sizeof *opp);
3938         return opp ? ofputil_decode_ofp10_phy_port(pp, opp) : EOF;
3939     } else {
3940         const struct ofp11_port *op = ofpbuf_try_pull(b, sizeof *op);
3941         return op ? ofputil_decode_ofp11_port(pp, op) : EOF;
3942     }
3943 }
3944
3945 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
3946  * 'ofp_version', returns the number of elements. */
3947 size_t ofputil_count_phy_ports(uint8_t ofp_version, struct ofpbuf *b)
3948 {
3949     return b->size / ofputil_get_phy_port_size(ofp_version);
3950 }
3951
3952 /* Returns the 'enum ofputil_action_code' corresponding to 'name' (e.g. if
3953  * 'name' is "output" then the return value is OFPUTIL_OFPAT10_OUTPUT), or -1 if
3954  * 'name' is not the name of any action.
3955  *
3956  * ofp-util.def lists the mapping from names to action. */
3957 int
3958 ofputil_action_code_from_name(const char *name)
3959 {
3960     static const char *names[OFPUTIL_N_ACTIONS] = {
3961         NULL,
3962 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)           NAME,
3963 #define OFPAT11_ACTION(ENUM, STRUCT, NAME)           NAME,
3964 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) NAME,
3965 #include "ofp-util.def"
3966     };
3967
3968     const char **p;
3969
3970     for (p = names; p < &names[ARRAY_SIZE(names)]; p++) {
3971         if (*p && !strcasecmp(name, *p)) {
3972             return p - names;
3973         }
3974     }
3975     return -1;
3976 }
3977
3978 /* Appends an action of the type specified by 'code' to 'buf' and returns the
3979  * action.  Initializes the parts of 'action' that identify it as having type
3980  * <ENUM> and length 'sizeof *action' and zeros the rest.  For actions that
3981  * have variable length, the length used and cleared is that of struct
3982  * <STRUCT>.  */
3983 void *
3984 ofputil_put_action(enum ofputil_action_code code, struct ofpbuf *buf)
3985 {
3986     switch (code) {
3987     case OFPUTIL_ACTION_INVALID:
3988         NOT_REACHED();
3989
3990 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                    \
3991     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
3992 #define OFPAT11_ACTION OFPAT10_ACTION
3993 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)        \
3994     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
3995 #include "ofp-util.def"
3996     }
3997     NOT_REACHED();
3998 }
3999
4000 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                        \
4001     void                                                        \
4002     ofputil_init_##ENUM(struct STRUCT *s)                       \
4003     {                                                           \
4004         memset(s, 0, sizeof *s);                                \
4005         s->type = htons(ENUM);                                  \
4006         s->len = htons(sizeof *s);                              \
4007     }                                                           \
4008                                                                 \
4009     struct STRUCT *                                             \
4010     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
4011     {                                                           \
4012         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
4013         ofputil_init_##ENUM(s);                                 \
4014         return s;                                               \
4015     }
4016 #define OFPAT11_ACTION OFPAT10_ACTION
4017 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)            \
4018     void                                                        \
4019     ofputil_init_##ENUM(struct STRUCT *s)                       \
4020     {                                                           \
4021         memset(s, 0, sizeof *s);                                \
4022         s->type = htons(OFPAT10_VENDOR);                        \
4023         s->len = htons(sizeof *s);                              \
4024         s->vendor = htonl(NX_VENDOR_ID);                        \
4025         s->subtype = htons(ENUM);                               \
4026     }                                                           \
4027                                                                 \
4028     struct STRUCT *                                             \
4029     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
4030     {                                                           \
4031         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
4032         ofputil_init_##ENUM(s);                                 \
4033         return s;                                               \
4034     }
4035 #include "ofp-util.def"
4036
4037 /* "Normalizes" the wildcards in 'rule'.  That means:
4038  *
4039  *    1. If the type of level N is known, then only the valid fields for that
4040  *       level may be specified.  For example, ARP does not have a TOS field,
4041  *       so nw_tos must be wildcarded if 'rule' specifies an ARP flow.
4042  *       Similarly, IPv4 does not have any IPv6 addresses, so ipv6_src and
4043  *       ipv6_dst (and other fields) must be wildcarded if 'rule' specifies an
4044  *       IPv4 flow.
4045  *
4046  *    2. If the type of level N is not known (or not understood by Open
4047  *       vSwitch), then no fields at all for that level may be specified.  For
4048  *       example, Open vSwitch does not understand SCTP, an L4 protocol, so the
4049  *       L4 fields tp_src and tp_dst must be wildcarded if 'rule' specifies an
4050  *       SCTP flow.
4051  */
4052 void
4053 ofputil_normalize_rule(struct cls_rule *rule)
4054 {
4055     enum {
4056         MAY_NW_ADDR     = 1 << 0, /* nw_src, nw_dst */
4057         MAY_TP_ADDR     = 1 << 1, /* tp_src, tp_dst */
4058         MAY_NW_PROTO    = 1 << 2, /* nw_proto */
4059         MAY_IPVx        = 1 << 3, /* tos, frag, ttl */
4060         MAY_ARP_SHA     = 1 << 4, /* arp_sha */
4061         MAY_ARP_THA     = 1 << 5, /* arp_tha */
4062         MAY_IPV6        = 1 << 6, /* ipv6_src, ipv6_dst, ipv6_label */
4063         MAY_ND_TARGET   = 1 << 7  /* nd_target */
4064     } may_match;
4065
4066     struct flow_wildcards wc;
4067
4068     /* Figure out what fields may be matched. */
4069     if (rule->flow.dl_type == htons(ETH_TYPE_IP)) {
4070         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_NW_ADDR;
4071         if (rule->flow.nw_proto == IPPROTO_TCP ||
4072             rule->flow.nw_proto == IPPROTO_UDP ||
4073             rule->flow.nw_proto == IPPROTO_ICMP) {
4074             may_match |= MAY_TP_ADDR;
4075         }
4076     } else if (rule->flow.dl_type == htons(ETH_TYPE_IPV6)) {
4077         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_IPV6;
4078         if (rule->flow.nw_proto == IPPROTO_TCP ||
4079             rule->flow.nw_proto == IPPROTO_UDP) {
4080             may_match |= MAY_TP_ADDR;
4081         } else if (rule->flow.nw_proto == IPPROTO_ICMPV6) {
4082             may_match |= MAY_TP_ADDR;
4083             if (rule->flow.tp_src == htons(ND_NEIGHBOR_SOLICIT)) {
4084                 may_match |= MAY_ND_TARGET | MAY_ARP_SHA;
4085             } else if (rule->flow.tp_src == htons(ND_NEIGHBOR_ADVERT)) {
4086                 may_match |= MAY_ND_TARGET | MAY_ARP_THA;
4087             }
4088         }
4089     } else if (rule->flow.dl_type == htons(ETH_TYPE_ARP)) {
4090         may_match = MAY_NW_PROTO | MAY_NW_ADDR | MAY_ARP_SHA | MAY_ARP_THA;
4091     } else {
4092         may_match = 0;
4093     }
4094
4095     /* Clear the fields that may not be matched. */
4096     wc = rule->wc;
4097     if (!(may_match & MAY_NW_ADDR)) {
4098         wc.nw_src_mask = wc.nw_dst_mask = htonl(0);
4099     }
4100     if (!(may_match & MAY_TP_ADDR)) {
4101         wc.tp_src_mask = wc.tp_dst_mask = htons(0);
4102     }
4103     if (!(may_match & MAY_NW_PROTO)) {
4104         wc.wildcards |= FWW_NW_PROTO;
4105     }
4106     if (!(may_match & MAY_IPVx)) {
4107         wc.wildcards |= FWW_NW_DSCP;
4108         wc.wildcards |= FWW_NW_ECN;
4109         wc.wildcards |= FWW_NW_TTL;
4110     }
4111     if (!(may_match & MAY_ARP_SHA)) {
4112         wc.wildcards |= FWW_ARP_SHA;
4113     }
4114     if (!(may_match & MAY_ARP_THA)) {
4115         wc.wildcards |= FWW_ARP_THA;
4116     }
4117     if (!(may_match & MAY_IPV6)) {
4118         wc.ipv6_src_mask = wc.ipv6_dst_mask = in6addr_any;
4119         wc.wildcards |= FWW_IPV6_LABEL;
4120     }
4121     if (!(may_match & MAY_ND_TARGET)) {
4122         wc.nd_target_mask = in6addr_any;
4123     }
4124
4125     /* Log any changes. */
4126     if (!flow_wildcards_equal(&wc, &rule->wc)) {
4127         bool log = !VLOG_DROP_INFO(&bad_ofmsg_rl);
4128         char *pre = log ? cls_rule_to_string(rule) : NULL;
4129
4130         rule->wc = wc;
4131         cls_rule_zero_wildcarded_fields(rule);
4132
4133         if (log) {
4134             char *post = cls_rule_to_string(rule);
4135             VLOG_INFO("normalization changed ofp_match, details:");
4136             VLOG_INFO(" pre: %s", pre);
4137             VLOG_INFO("post: %s", post);
4138             free(pre);
4139             free(post);
4140         }
4141     }
4142 }
4143
4144 /* Parses a key or a key-value pair from '*stringp'.
4145  *
4146  * On success: Stores the key into '*keyp'.  Stores the value, if present, into
4147  * '*valuep', otherwise an empty string.  Advances '*stringp' past the end of
4148  * the key-value pair, preparing it for another call.  '*keyp' and '*valuep'
4149  * are substrings of '*stringp' created by replacing some of its bytes by null
4150  * terminators.  Returns true.
4151  *
4152  * If '*stringp' is just white space or commas, sets '*keyp' and '*valuep' to
4153  * NULL and returns false. */
4154 bool
4155 ofputil_parse_key_value(char **stringp, char **keyp, char **valuep)
4156 {
4157     char *pos, *key, *value;
4158     size_t key_len;
4159
4160     pos = *stringp;
4161     pos += strspn(pos, ", \t\r\n");
4162     if (*pos == '\0') {
4163         *keyp = *valuep = NULL;
4164         return false;
4165     }
4166
4167     key = pos;
4168     key_len = strcspn(pos, ":=(, \t\r\n");
4169     if (key[key_len] == ':' || key[key_len] == '=') {
4170         /* The value can be separated by a colon. */
4171         size_t value_len;
4172
4173         value = key + key_len + 1;
4174         value_len = strcspn(value, ", \t\r\n");
4175         pos = value + value_len + (value[value_len] != '\0');
4176         value[value_len] = '\0';
4177     } else if (key[key_len] == '(') {
4178         /* The value can be surrounded by balanced parentheses.  The outermost
4179          * set of parentheses is removed. */
4180         int level = 1;
4181         size_t value_len;
4182
4183         value = key + key_len + 1;
4184         for (value_len = 0; level > 0; value_len++) {
4185             switch (value[value_len]) {
4186             case '\0':
4187                 level = 0;
4188                 break;
4189
4190             case '(':
4191                 level++;
4192                 break;
4193
4194             case ')':
4195                 level--;
4196                 break;
4197             }
4198         }
4199         value[value_len - 1] = '\0';
4200         pos = value + value_len;
4201     } else {
4202         /* There might be no value at all. */
4203         value = key + key_len;  /* Will become the empty string below. */
4204         pos = key + key_len + (key[key_len] != '\0');
4205     }
4206     key[key_len] = '\0';
4207
4208     *stringp = pos;
4209     *keyp = key;
4210     *valuep = value;
4211     return true;
4212 }