99f92a8cca28f074052cea486bcb76917ac35d12
[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
683     static const struct ofputil_msg_category nxt_category = {
684         "Nicira extension message",
685         nxt_messages, ARRAY_SIZE(nxt_messages),
686         OFPERR_OFPBRC_BAD_SUBTYPE
687     };
688
689     const struct ofp_vendor_header *ovh;
690     const struct nicira_header *nh;
691
692     if (length < sizeof(struct ofp_vendor_header)) {
693         if (length == ntohs(oh->length)) {
694             VLOG_WARN_RL(&bad_ofmsg_rl, "truncated vendor message");
695         }
696         return OFPERR_OFPBRC_BAD_LEN;
697     }
698
699     ovh = (const struct ofp_vendor_header *) oh;
700     if (ovh->vendor != htonl(NX_VENDOR_ID)) {
701         VLOG_WARN_RL(&bad_ofmsg_rl, "received vendor message for unknown "
702                      "vendor %"PRIx32, ntohl(ovh->vendor));
703         return OFPERR_OFPBRC_BAD_VENDOR;
704     }
705
706     if (length < sizeof(struct nicira_header)) {
707         if (length == ntohs(oh->length)) {
708             VLOG_WARN_RL(&bad_ofmsg_rl, "received Nicira vendor message of "
709                          "length %u (expected at least %zu)",
710                          ntohs(ovh->header.length),
711                          sizeof(struct nicira_header));
712         }
713         return OFPERR_OFPBRC_BAD_LEN;
714     }
715
716     nh = (const struct nicira_header *) oh;
717     return ofputil_lookup_openflow_message(&nxt_category, oh->version,
718                                            ntohl(nh->subtype), typep);
719 }
720
721 static enum ofperr
722 check_nxstats_msg(const struct ofp_header *oh, size_t length)
723 {
724     const struct ofp_stats_msg *osm = (const struct ofp_stats_msg *) oh;
725     ovs_be32 vendor;
726
727     if (length < sizeof(struct ofp_vendor_stats_msg)) {
728         if (length == ntohs(oh->length)) {
729             VLOG_WARN_RL(&bad_ofmsg_rl, "truncated vendor stats message");
730         }
731         return OFPERR_OFPBRC_BAD_LEN;
732     }
733
734     memcpy(&vendor, osm + 1, sizeof vendor);
735     if (vendor != htonl(NX_VENDOR_ID)) {
736         VLOG_WARN_RL(&bad_ofmsg_rl, "received vendor stats message for "
737                      "unknown vendor %"PRIx32, ntohl(vendor));
738         return OFPERR_OFPBRC_BAD_VENDOR;
739     }
740
741     if (length < sizeof(struct nicira_stats_msg)) {
742         if (length == ntohs(osm->header.length)) {
743             VLOG_WARN_RL(&bad_ofmsg_rl, "truncated Nicira stats message");
744         }
745         return OFPERR_OFPBRC_BAD_LEN;
746     }
747
748     return 0;
749 }
750
751 static enum ofperr
752 ofputil_decode_nxst_request(const struct ofp_header *oh, size_t length,
753                             const struct ofputil_msg_type **typep)
754 {
755     static const struct ofputil_msg_type nxst_requests[] = {
756         { OFPUTIL_NXST_FLOW_REQUEST, OFP10_VERSION,
757           NXST_FLOW, "NXST_FLOW request",
758           sizeof(struct nx_flow_stats_request), 8 },
759
760         { OFPUTIL_NXST_AGGREGATE_REQUEST, OFP10_VERSION,
761           NXST_AGGREGATE, "NXST_AGGREGATE request",
762           sizeof(struct nx_aggregate_stats_request), 8 },
763     };
764
765     static const struct ofputil_msg_category nxst_request_category = {
766         "Nicira extension statistics request",
767         nxst_requests, ARRAY_SIZE(nxst_requests),
768         OFPERR_OFPBRC_BAD_SUBTYPE
769     };
770
771     const struct nicira_stats_msg *nsm;
772     enum ofperr error;
773
774     error = check_nxstats_msg(oh, length);
775     if (error) {
776         return error;
777     }
778
779     nsm = (struct nicira_stats_msg *) oh;
780     return ofputil_lookup_openflow_message(&nxst_request_category, oh->version,
781                                            ntohl(nsm->subtype), typep);
782 }
783
784 static enum ofperr
785 ofputil_decode_nxst_reply(const struct ofp_header *oh, size_t length,
786                           const struct ofputil_msg_type **typep)
787 {
788     static const struct ofputil_msg_type nxst_replies[] = {
789         { OFPUTIL_NXST_FLOW_REPLY, OFP10_VERSION,
790           NXST_FLOW, "NXST_FLOW reply",
791           sizeof(struct nicira_stats_msg), 8 },
792
793         { OFPUTIL_NXST_AGGREGATE_REPLY, OFP10_VERSION,
794           NXST_AGGREGATE, "NXST_AGGREGATE reply",
795           sizeof(struct nx_aggregate_stats_reply), 0 },
796     };
797
798     static const struct ofputil_msg_category nxst_reply_category = {
799         "Nicira extension statistics reply",
800         nxst_replies, ARRAY_SIZE(nxst_replies),
801         OFPERR_OFPBRC_BAD_SUBTYPE
802     };
803
804     const struct nicira_stats_msg *nsm;
805     enum ofperr error;
806
807     error = check_nxstats_msg(oh, length);
808     if (error) {
809         return error;
810     }
811
812     nsm = (struct nicira_stats_msg *) oh;
813     return ofputil_lookup_openflow_message(&nxst_reply_category, oh->version,
814                                            ntohl(nsm->subtype), typep);
815 }
816
817 static enum ofperr
818 check_stats_msg(const struct ofp_header *oh, size_t length)
819 {
820     if (length < sizeof(struct ofp_stats_msg)) {
821         if (length == ntohs(oh->length)) {
822             VLOG_WARN_RL(&bad_ofmsg_rl, "truncated stats message");
823         }
824         return OFPERR_OFPBRC_BAD_LEN;
825     }
826
827     return 0;
828 }
829
830 static enum ofperr
831 ofputil_decode_ofpst_request(const struct ofp_header *oh, size_t length,
832                              const struct ofputil_msg_type **typep)
833 {
834     static const struct ofputil_msg_type ofpst_requests[] = {
835         { OFPUTIL_OFPST_DESC_REQUEST, OFP10_VERSION,
836           OFPST_DESC, "OFPST_DESC request",
837           sizeof(struct ofp_stats_msg), 0 },
838
839         { OFPUTIL_OFPST_FLOW_REQUEST, OFP10_VERSION,
840           OFPST_FLOW, "OFPST_FLOW request",
841           sizeof(struct ofp_flow_stats_request), 0 },
842
843         { OFPUTIL_OFPST_AGGREGATE_REQUEST, OFP10_VERSION,
844           OFPST_AGGREGATE, "OFPST_AGGREGATE request",
845           sizeof(struct ofp_flow_stats_request), 0 },
846
847         { OFPUTIL_OFPST_TABLE_REQUEST, OFP10_VERSION,
848           OFPST_TABLE, "OFPST_TABLE request",
849           sizeof(struct ofp_stats_msg), 0 },
850
851         { OFPUTIL_OFPST_PORT_REQUEST, OFP10_VERSION,
852           OFPST_PORT, "OFPST_PORT request",
853           sizeof(struct ofp_port_stats_request), 0 },
854
855         { OFPUTIL_OFPST_QUEUE_REQUEST, OFP10_VERSION,
856           OFPST_QUEUE, "OFPST_QUEUE request",
857           sizeof(struct ofp_queue_stats_request), 0 },
858
859         { OFPUTIL_OFPST_PORT_DESC_REQUEST, OFP10_VERSION,
860           OFPST_PORT_DESC, "OFPST_PORT_DESC request",
861           sizeof(struct ofp_stats_msg), 0 },
862
863         { 0, 0,
864           OFPST_VENDOR, "OFPST_VENDOR request",
865           sizeof(struct ofp_vendor_stats_msg), 1 },
866     };
867
868     static const struct ofputil_msg_category ofpst_request_category = {
869         "OpenFlow statistics",
870         ofpst_requests, ARRAY_SIZE(ofpst_requests),
871         OFPERR_OFPBRC_BAD_STAT
872     };
873
874     const struct ofp_stats_msg *request = (const struct ofp_stats_msg *) oh;
875     enum ofperr error;
876
877     error = check_stats_msg(oh, length);
878     if (error) {
879         return error;
880     }
881
882     error = ofputil_lookup_openflow_message(&ofpst_request_category,
883                                             oh->version, ntohs(request->type),
884                                             typep);
885     if (!error && request->type == htons(OFPST_VENDOR)) {
886         error = ofputil_decode_nxst_request(oh, length, typep);
887     }
888     return error;
889 }
890
891 static enum ofperr
892 ofputil_decode_ofpst_reply(const struct ofp_header *oh, size_t length,
893                            const struct ofputil_msg_type **typep)
894 {
895     static const struct ofputil_msg_type ofpst_replies[] = {
896         { OFPUTIL_OFPST_DESC_REPLY, OFP10_VERSION,
897           OFPST_DESC, "OFPST_DESC reply",
898           sizeof(struct ofp_desc_stats), 0 },
899
900         { OFPUTIL_OFPST_FLOW_REPLY, OFP10_VERSION,
901           OFPST_FLOW, "OFPST_FLOW reply",
902           sizeof(struct ofp_stats_msg), 1 },
903
904         { OFPUTIL_OFPST_AGGREGATE_REPLY, OFP10_VERSION,
905           OFPST_AGGREGATE, "OFPST_AGGREGATE reply",
906           sizeof(struct ofp_aggregate_stats_reply), 0 },
907
908         { OFPUTIL_OFPST_TABLE_REPLY, OFP10_VERSION,
909           OFPST_TABLE, "OFPST_TABLE reply",
910           sizeof(struct ofp_stats_msg), sizeof(struct ofp_table_stats) },
911
912         { OFPUTIL_OFPST_PORT_REPLY, OFP10_VERSION,
913           OFPST_PORT, "OFPST_PORT reply",
914           sizeof(struct ofp_stats_msg), sizeof(struct ofp_port_stats) },
915
916         { OFPUTIL_OFPST_QUEUE_REPLY, OFP10_VERSION,
917           OFPST_QUEUE, "OFPST_QUEUE reply",
918           sizeof(struct ofp_stats_msg), sizeof(struct ofp_queue_stats) },
919
920         { OFPUTIL_OFPST_PORT_DESC_REPLY, OFP10_VERSION,
921           OFPST_PORT_DESC, "OFPST_PORT_DESC reply",
922           sizeof(struct ofp_stats_msg), sizeof(struct ofp10_phy_port) },
923
924         { 0, 0,
925           OFPST_VENDOR, "OFPST_VENDOR reply",
926           sizeof(struct ofp_vendor_stats_msg), 1 },
927     };
928
929     static const struct ofputil_msg_category ofpst_reply_category = {
930         "OpenFlow statistics",
931         ofpst_replies, ARRAY_SIZE(ofpst_replies),
932         OFPERR_OFPBRC_BAD_STAT
933     };
934
935     const struct ofp_stats_msg *reply = (const struct ofp_stats_msg *) oh;
936     enum ofperr error;
937
938     error = check_stats_msg(oh, length);
939     if (error) {
940         return error;
941     }
942
943     error = ofputil_lookup_openflow_message(&ofpst_reply_category, oh->version,
944                                            ntohs(reply->type), typep);
945     if (!error && reply->type == htons(OFPST_VENDOR)) {
946         error = ofputil_decode_nxst_reply(oh, length, typep);
947     }
948     return error;
949 }
950
951 static enum ofperr
952 ofputil_decode_msg_type__(const struct ofp_header *oh, size_t length,
953                           const struct ofputil_msg_type **typep)
954 {
955     static const struct ofputil_msg_type ofpt_messages[] = {
956         { OFPUTIL_OFPT_HELLO, OFP10_VERSION,
957           OFPT_HELLO, "OFPT_HELLO",
958           sizeof(struct ofp_hello), 1 },
959
960         { OFPUTIL_OFPT_ERROR, 0,
961           OFPT_ERROR, "OFPT_ERROR",
962           sizeof(struct ofp_error_msg), 1 },
963
964         { OFPUTIL_OFPT_ECHO_REQUEST, OFP10_VERSION,
965           OFPT_ECHO_REQUEST, "OFPT_ECHO_REQUEST",
966           sizeof(struct ofp_header), 1 },
967
968         { OFPUTIL_OFPT_ECHO_REPLY, OFP10_VERSION,
969           OFPT_ECHO_REPLY, "OFPT_ECHO_REPLY",
970           sizeof(struct ofp_header), 1 },
971
972         { OFPUTIL_OFPT_FEATURES_REQUEST, OFP10_VERSION,
973           OFPT_FEATURES_REQUEST, "OFPT_FEATURES_REQUEST",
974           sizeof(struct ofp_header), 0 },
975
976         { OFPUTIL_OFPT_FEATURES_REPLY, OFP10_VERSION,
977           OFPT_FEATURES_REPLY, "OFPT_FEATURES_REPLY",
978           sizeof(struct ofp_switch_features), sizeof(struct ofp10_phy_port) },
979         { OFPUTIL_OFPT_FEATURES_REPLY, OFP11_VERSION,
980           OFPT_FEATURES_REPLY, "OFPT_FEATURES_REPLY",
981           sizeof(struct ofp_switch_features), sizeof(struct ofp11_port) },
982
983         { OFPUTIL_OFPT_GET_CONFIG_REQUEST, OFP10_VERSION,
984           OFPT_GET_CONFIG_REQUEST, "OFPT_GET_CONFIG_REQUEST",
985           sizeof(struct ofp_header), 0 },
986
987         { OFPUTIL_OFPT_GET_CONFIG_REPLY, OFP10_VERSION,
988           OFPT_GET_CONFIG_REPLY, "OFPT_GET_CONFIG_REPLY",
989           sizeof(struct ofp_switch_config), 0 },
990
991         { OFPUTIL_OFPT_SET_CONFIG, OFP10_VERSION,
992           OFPT_SET_CONFIG, "OFPT_SET_CONFIG",
993           sizeof(struct ofp_switch_config), 0 },
994
995         { OFPUTIL_OFPT_PACKET_IN, OFP10_VERSION,
996           OFPT_PACKET_IN, "OFPT_PACKET_IN",
997           offsetof(struct ofp_packet_in, data), 1 },
998
999         { OFPUTIL_OFPT_FLOW_REMOVED, OFP10_VERSION,
1000           OFPT_FLOW_REMOVED, "OFPT_FLOW_REMOVED",
1001           sizeof(struct ofp_flow_removed), 0 },
1002
1003         { OFPUTIL_OFPT_PORT_STATUS, OFP10_VERSION,
1004           OFPT_PORT_STATUS, "OFPT_PORT_STATUS",
1005           sizeof(struct ofp_port_status) + sizeof(struct ofp10_phy_port), 0 },
1006         { OFPUTIL_OFPT_PORT_STATUS, OFP11_VERSION,
1007           OFPT_PORT_STATUS, "OFPT_PORT_STATUS",
1008           sizeof(struct ofp_port_status) + sizeof(struct ofp11_port), 0 },
1009
1010         { OFPUTIL_OFPT_PACKET_OUT, OFP10_VERSION,
1011           OFPT_PACKET_OUT, "OFPT_PACKET_OUT",
1012           sizeof(struct ofp_packet_out), 1 },
1013
1014         { OFPUTIL_OFPT_FLOW_MOD, OFP10_VERSION,
1015           OFPT_FLOW_MOD, "OFPT_FLOW_MOD",
1016           sizeof(struct ofp_flow_mod), 1 },
1017
1018         { OFPUTIL_OFPT_PORT_MOD, OFP10_VERSION,
1019           OFPT10_PORT_MOD, "OFPT_PORT_MOD",
1020           sizeof(struct ofp10_port_mod), 0 },
1021         { OFPUTIL_OFPT_PORT_MOD, OFP11_VERSION,
1022           OFPT11_PORT_MOD, "OFPT_PORT_MOD",
1023           sizeof(struct ofp11_port_mod), 0 },
1024
1025         { 0, OFP10_VERSION,
1026           OFPT10_STATS_REQUEST, "OFPT_STATS_REQUEST",
1027           sizeof(struct ofp_stats_msg), 1 },
1028
1029         { 0, OFP10_VERSION,
1030           OFPT10_STATS_REPLY, "OFPT_STATS_REPLY",
1031           sizeof(struct ofp_stats_msg), 1 },
1032
1033         { OFPUTIL_OFPT_BARRIER_REQUEST, OFP10_VERSION,
1034           OFPT10_BARRIER_REQUEST, "OFPT_BARRIER_REQUEST",
1035           sizeof(struct ofp_header), 0 },
1036
1037         { OFPUTIL_OFPT_BARRIER_REPLY, OFP10_VERSION,
1038           OFPT10_BARRIER_REPLY, "OFPT_BARRIER_REPLY",
1039           sizeof(struct ofp_header), 0 },
1040
1041         { 0, 0,
1042           OFPT_VENDOR, "OFPT_VENDOR",
1043           sizeof(struct ofp_vendor_header), 1 },
1044     };
1045
1046     static const struct ofputil_msg_category ofpt_category = {
1047         "OpenFlow message",
1048         ofpt_messages, ARRAY_SIZE(ofpt_messages),
1049         OFPERR_OFPBRC_BAD_TYPE
1050     };
1051
1052     enum ofperr error;
1053
1054     error = ofputil_lookup_openflow_message(&ofpt_category, oh->version,
1055                                             oh->type, typep);
1056     if (!error) {
1057         switch ((oh->version << 8) | oh->type) {
1058         case (OFP10_VERSION << 8) | OFPT_VENDOR:
1059         case (OFP11_VERSION << 8) | OFPT_VENDOR:
1060             error = ofputil_decode_vendor(oh, length, typep);
1061             break;
1062
1063         case (OFP10_VERSION << 8) | OFPT10_STATS_REQUEST:
1064         case (OFP11_VERSION << 8) | OFPT11_STATS_REQUEST:
1065             error = ofputil_decode_ofpst_request(oh, length, typep);
1066             break;
1067
1068         case (OFP10_VERSION << 8) | OFPT10_STATS_REPLY:
1069         case (OFP11_VERSION << 8) | OFPT11_STATS_REPLY:
1070             error = ofputil_decode_ofpst_reply(oh, length, typep);
1071
1072         default:
1073             break;
1074         }
1075     }
1076     return error;
1077 }
1078
1079 /* Decodes the message type represented by 'oh'.  Returns 0 if successful or an
1080  * OpenFlow error code on failure.  Either way, stores in '*typep' a type
1081  * structure that can be inspected with the ofputil_msg_type_*() functions.
1082  *
1083  * oh->length must indicate the correct length of the message (and must be at
1084  * least sizeof(struct ofp_header)).
1085  *
1086  * Success indicates that 'oh' is at least as long as the minimum-length
1087  * message of its type. */
1088 enum ofperr
1089 ofputil_decode_msg_type(const struct ofp_header *oh,
1090                         const struct ofputil_msg_type **typep)
1091 {
1092     size_t length = ntohs(oh->length);
1093     enum ofperr error;
1094
1095     error = ofputil_decode_msg_type__(oh, length, typep);
1096     if (!error) {
1097         error = ofputil_check_length(*typep, length);
1098     }
1099     if (error) {
1100         *typep = &ofputil_invalid_type;
1101     }
1102     return error;
1103 }
1104
1105 /* Decodes the message type represented by 'oh', of which only the first
1106  * 'length' bytes are available.  Returns 0 if successful or an OpenFlow error
1107  * code on failure.  Either way, stores in '*typep' a type structure that can
1108  * be inspected with the ofputil_msg_type_*() functions.  */
1109 enum ofperr
1110 ofputil_decode_msg_type_partial(const struct ofp_header *oh, size_t length,
1111                                 const struct ofputil_msg_type **typep)
1112 {
1113     enum ofperr error;
1114
1115     error = (length >= sizeof *oh
1116              ? ofputil_decode_msg_type__(oh, length, typep)
1117              : OFPERR_OFPBRC_BAD_LEN);
1118     if (error) {
1119         *typep = &ofputil_invalid_type;
1120     }
1121     return error;
1122 }
1123
1124 /* Returns an OFPUTIL_* message type code for 'type'. */
1125 enum ofputil_msg_code
1126 ofputil_msg_type_code(const struct ofputil_msg_type *type)
1127 {
1128     return type->code;
1129 }
1130 \f
1131 /* Protocols. */
1132
1133 struct proto_abbrev {
1134     enum ofputil_protocol protocol;
1135     const char *name;
1136 };
1137
1138 /* Most users really don't care about some of the differences between
1139  * protocols.  These abbreviations help with that. */
1140 static const struct proto_abbrev proto_abbrevs[] = {
1141     { OFPUTIL_P_ANY,      "any" },
1142     { OFPUTIL_P_OF10_ANY, "OpenFlow10" },
1143     { OFPUTIL_P_NXM_ANY,  "NXM" },
1144 };
1145 #define N_PROTO_ABBREVS ARRAY_SIZE(proto_abbrevs)
1146
1147 enum ofputil_protocol ofputil_flow_dump_protocols[] = {
1148     OFPUTIL_P_NXM,
1149     OFPUTIL_P_OF10,
1150 };
1151 size_t ofputil_n_flow_dump_protocols = ARRAY_SIZE(ofputil_flow_dump_protocols);
1152
1153 /* Returns the ofputil_protocol that is initially in effect on an OpenFlow
1154  * connection that has negotiated the given 'version'.  'version' should
1155  * normally be an 8-bit OpenFlow version identifier (e.g. 0x01 for OpenFlow
1156  * 1.0, 0x02 for OpenFlow 1.1).  Returns 0 if 'version' is not supported or
1157  * outside the valid range.  */
1158 enum ofputil_protocol
1159 ofputil_protocol_from_ofp_version(int version)
1160 {
1161     switch (version) {
1162     case OFP10_VERSION: return OFPUTIL_P_OF10;
1163     default: return 0;
1164     }
1165 }
1166
1167 /* Returns the OpenFlow protocol version number (e.g. OFP10_VERSION or
1168  * OFP11_VERSION) that corresponds to 'protocol'. */
1169 uint8_t
1170 ofputil_protocol_to_ofp_version(enum ofputil_protocol protocol)
1171 {
1172     switch (protocol) {
1173     case OFPUTIL_P_OF10:
1174     case OFPUTIL_P_OF10_TID:
1175     case OFPUTIL_P_NXM:
1176     case OFPUTIL_P_NXM_TID:
1177         return OFP10_VERSION;
1178     }
1179
1180     NOT_REACHED();
1181 }
1182
1183 /* Returns true if 'protocol' is a single OFPUTIL_P_* value, false
1184  * otherwise. */
1185 bool
1186 ofputil_protocol_is_valid(enum ofputil_protocol protocol)
1187 {
1188     return protocol & OFPUTIL_P_ANY && is_pow2(protocol);
1189 }
1190
1191 /* Returns the equivalent of 'protocol' with the Nicira flow_mod_table_id
1192  * extension turned on or off if 'enable' is true or false, respectively.
1193  *
1194  * This extension is only useful for protocols whose "standard" version does
1195  * not allow specific tables to be modified.  In particular, this is true of
1196  * OpenFlow 1.0.  In later versions of OpenFlow, a flow_mod request always
1197  * specifies a table ID and so there is no need for such an extension.  When
1198  * 'protocol' is such a protocol that doesn't need a flow_mod_table_id
1199  * extension, this function just returns its 'protocol' argument unchanged
1200  * regardless of the value of 'enable'.  */
1201 enum ofputil_protocol
1202 ofputil_protocol_set_tid(enum ofputil_protocol protocol, bool enable)
1203 {
1204     switch (protocol) {
1205     case OFPUTIL_P_OF10:
1206     case OFPUTIL_P_OF10_TID:
1207         return enable ? OFPUTIL_P_OF10_TID : OFPUTIL_P_OF10;
1208
1209     case OFPUTIL_P_NXM:
1210     case OFPUTIL_P_NXM_TID:
1211         return enable ? OFPUTIL_P_NXM_TID : OFPUTIL_P_NXM;
1212
1213     default:
1214         NOT_REACHED();
1215     }
1216 }
1217
1218 /* Returns the "base" version of 'protocol'.  That is, if 'protocol' includes
1219  * some extension to a standard protocol version, the return value is the
1220  * standard version of that protocol without any extension.  If 'protocol' is a
1221  * standard protocol version, returns 'protocol' unchanged. */
1222 enum ofputil_protocol
1223 ofputil_protocol_to_base(enum ofputil_protocol protocol)
1224 {
1225     return ofputil_protocol_set_tid(protocol, false);
1226 }
1227
1228 /* Returns 'new_base' with any extensions taken from 'cur'. */
1229 enum ofputil_protocol
1230 ofputil_protocol_set_base(enum ofputil_protocol cur,
1231                           enum ofputil_protocol new_base)
1232 {
1233     bool tid = (cur & OFPUTIL_P_TID) != 0;
1234
1235     switch (new_base) {
1236     case OFPUTIL_P_OF10:
1237     case OFPUTIL_P_OF10_TID:
1238         return ofputil_protocol_set_tid(OFPUTIL_P_OF10, tid);
1239
1240     case OFPUTIL_P_NXM:
1241     case OFPUTIL_P_NXM_TID:
1242         return ofputil_protocol_set_tid(OFPUTIL_P_NXM, tid);
1243
1244     default:
1245         NOT_REACHED();
1246     }
1247 }
1248
1249 /* Returns a string form of 'protocol', if a simple form exists (that is, if
1250  * 'protocol' is either a single protocol or it is a combination of protocols
1251  * that have a single abbreviation).  Otherwise, returns NULL. */
1252 const char *
1253 ofputil_protocol_to_string(enum ofputil_protocol protocol)
1254 {
1255     const struct proto_abbrev *p;
1256
1257     /* Use a "switch" statement for single-bit names so that we get a compiler
1258      * warning if we forget any. */
1259     switch (protocol) {
1260     case OFPUTIL_P_NXM:
1261         return "NXM-table_id";
1262
1263     case OFPUTIL_P_NXM_TID:
1264         return "NXM+table_id";
1265
1266     case OFPUTIL_P_OF10:
1267         return "OpenFlow10-table_id";
1268
1269     case OFPUTIL_P_OF10_TID:
1270         return "OpenFlow10+table_id";
1271     }
1272
1273     /* Check abbreviations. */
1274     for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
1275         if (protocol == p->protocol) {
1276             return p->name;
1277         }
1278     }
1279
1280     return NULL;
1281 }
1282
1283 /* Returns a string that represents 'protocols'.  The return value might be a
1284  * comma-separated list if 'protocols' doesn't have a simple name.  The return
1285  * value is "none" if 'protocols' is 0.
1286  *
1287  * The caller must free the returned string (with free()). */
1288 char *
1289 ofputil_protocols_to_string(enum ofputil_protocol protocols)
1290 {
1291     struct ds s;
1292
1293     assert(!(protocols & ~OFPUTIL_P_ANY));
1294     if (protocols == 0) {
1295         return xstrdup("none");
1296     }
1297
1298     ds_init(&s);
1299     while (protocols) {
1300         const struct proto_abbrev *p;
1301         int i;
1302
1303         if (s.length) {
1304             ds_put_char(&s, ',');
1305         }
1306
1307         for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
1308             if ((protocols & p->protocol) == p->protocol) {
1309                 ds_put_cstr(&s, p->name);
1310                 protocols &= ~p->protocol;
1311                 goto match;
1312             }
1313         }
1314
1315         for (i = 0; i < CHAR_BIT * sizeof(enum ofputil_protocol); i++) {
1316             enum ofputil_protocol bit = 1u << i;
1317
1318             if (protocols & bit) {
1319                 ds_put_cstr(&s, ofputil_protocol_to_string(bit));
1320                 protocols &= ~bit;
1321                 goto match;
1322             }
1323         }
1324         NOT_REACHED();
1325
1326     match: ;
1327     }
1328     return ds_steal_cstr(&s);
1329 }
1330
1331 static enum ofputil_protocol
1332 ofputil_protocol_from_string__(const char *s, size_t n)
1333 {
1334     const struct proto_abbrev *p;
1335     int i;
1336
1337     for (i = 0; i < CHAR_BIT * sizeof(enum ofputil_protocol); i++) {
1338         enum ofputil_protocol bit = 1u << i;
1339         const char *name = ofputil_protocol_to_string(bit);
1340
1341         if (name && n == strlen(name) && !strncasecmp(s, name, n)) {
1342             return bit;
1343         }
1344     }
1345
1346     for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
1347         if (n == strlen(p->name) && !strncasecmp(s, p->name, n)) {
1348             return p->protocol;
1349         }
1350     }
1351
1352     return 0;
1353 }
1354
1355 /* Returns the nonempty set of protocols represented by 's', which can be a
1356  * single protocol name or abbreviation or a comma-separated list of them.
1357  *
1358  * Aborts the program with an error message if 's' is invalid. */
1359 enum ofputil_protocol
1360 ofputil_protocols_from_string(const char *s)
1361 {
1362     const char *orig_s = s;
1363     enum ofputil_protocol protocols;
1364
1365     protocols = 0;
1366     while (*s) {
1367         enum ofputil_protocol p;
1368         size_t n;
1369
1370         n = strcspn(s, ",");
1371         if (n == 0) {
1372             s++;
1373             continue;
1374         }
1375
1376         p = ofputil_protocol_from_string__(s, n);
1377         if (!p) {
1378             ovs_fatal(0, "%.*s: unknown flow protocol", (int) n, s);
1379         }
1380         protocols |= p;
1381
1382         s += n;
1383     }
1384
1385     if (!protocols) {
1386         ovs_fatal(0, "%s: no flow protocol specified", orig_s);
1387     }
1388     return protocols;
1389 }
1390
1391 bool
1392 ofputil_packet_in_format_is_valid(enum nx_packet_in_format packet_in_format)
1393 {
1394     switch (packet_in_format) {
1395     case NXPIF_OPENFLOW10:
1396     case NXPIF_NXM:
1397         return true;
1398     }
1399
1400     return false;
1401 }
1402
1403 const char *
1404 ofputil_packet_in_format_to_string(enum nx_packet_in_format packet_in_format)
1405 {
1406     switch (packet_in_format) {
1407     case NXPIF_OPENFLOW10:
1408         return "openflow10";
1409     case NXPIF_NXM:
1410         return "nxm";
1411     default:
1412         NOT_REACHED();
1413     }
1414 }
1415
1416 int
1417 ofputil_packet_in_format_from_string(const char *s)
1418 {
1419     return (!strcmp(s, "openflow10") ? NXPIF_OPENFLOW10
1420             : !strcmp(s, "nxm") ? NXPIF_NXM
1421             : -1);
1422 }
1423
1424 static bool
1425 regs_fully_wildcarded(const struct flow_wildcards *wc)
1426 {
1427     int i;
1428
1429     for (i = 0; i < FLOW_N_REGS; i++) {
1430         if (wc->reg_masks[i] != 0) {
1431             return false;
1432         }
1433     }
1434     return true;
1435 }
1436
1437 /* Returns a bit-mask of ofputil_protocols that can be used for sending 'rule'
1438  * to a switch (e.g. to add or remove a flow).  Only NXM can handle tunnel IDs,
1439  * registers, or fixing the Ethernet multicast bit.  Otherwise, it's better to
1440  * use OpenFlow 1.0 protocol for backward compatibility. */
1441 enum ofputil_protocol
1442 ofputil_usable_protocols(const struct cls_rule *rule)
1443 {
1444     const struct flow_wildcards *wc = &rule->wc;
1445
1446     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 12);
1447
1448     /* NXM and OF1.1+ supports bitwise matching on ethernet addresses. */
1449     if (!eth_mask_is_exact(wc->dl_src_mask)
1450         && !eth_addr_is_zero(wc->dl_src_mask)) {
1451         return OFPUTIL_P_NXM_ANY;
1452     }
1453     if (!eth_mask_is_exact(wc->dl_dst_mask)
1454         && !eth_addr_is_zero(wc->dl_dst_mask)) {
1455         return OFPUTIL_P_NXM_ANY;
1456     }
1457
1458     /* NXM and OF1.1+ support matching metadata. */
1459     if (wc->metadata_mask != htonll(0)) {
1460         return OFPUTIL_P_NXM_ANY;
1461     }
1462
1463     /* Only NXM supports matching ARP hardware addresses. */
1464     if (!(wc->wildcards & FWW_ARP_SHA) || !(wc->wildcards & FWW_ARP_THA)) {
1465         return OFPUTIL_P_NXM_ANY;
1466     }
1467
1468     /* Only NXM supports matching IPv6 traffic. */
1469     if (!(wc->wildcards & FWW_DL_TYPE)
1470             && (rule->flow.dl_type == htons(ETH_TYPE_IPV6))) {
1471         return OFPUTIL_P_NXM_ANY;
1472     }
1473
1474     /* Only NXM supports matching registers. */
1475     if (!regs_fully_wildcarded(wc)) {
1476         return OFPUTIL_P_NXM_ANY;
1477     }
1478
1479     /* Only NXM supports matching tun_id. */
1480     if (wc->tun_id_mask != htonll(0)) {
1481         return OFPUTIL_P_NXM_ANY;
1482     }
1483
1484     /* Only NXM supports matching fragments. */
1485     if (wc->nw_frag_mask) {
1486         return OFPUTIL_P_NXM_ANY;
1487     }
1488
1489     /* Only NXM supports matching IPv6 flow label. */
1490     if (!(wc->wildcards & FWW_IPV6_LABEL)) {
1491         return OFPUTIL_P_NXM_ANY;
1492     }
1493
1494     /* Only NXM supports matching IP ECN bits. */
1495     if (!(wc->wildcards & FWW_NW_ECN)) {
1496         return OFPUTIL_P_NXM_ANY;
1497     }
1498
1499     /* Only NXM supports matching IP TTL/hop limit. */
1500     if (!(wc->wildcards & FWW_NW_TTL)) {
1501         return OFPUTIL_P_NXM_ANY;
1502     }
1503
1504     /* Only NXM supports non-CIDR IPv4 address masks. */
1505     if (!ip_is_cidr(wc->nw_src_mask) || !ip_is_cidr(wc->nw_dst_mask)) {
1506         return OFPUTIL_P_NXM_ANY;
1507     }
1508
1509     /* Only NXM supports bitwise matching on transport port. */
1510     if ((wc->tp_src_mask && wc->tp_src_mask != htons(UINT16_MAX)) ||
1511         (wc->tp_dst_mask && wc->tp_dst_mask != htons(UINT16_MAX))) {
1512         return OFPUTIL_P_NXM_ANY;
1513     }
1514
1515     /* Other formats can express this rule. */
1516     return OFPUTIL_P_ANY;
1517 }
1518
1519 /* Returns an OpenFlow message that, sent on an OpenFlow connection whose
1520  * protocol is 'current', at least partly transitions the protocol to 'want'.
1521  * Stores in '*next' the protocol that will be in effect on the OpenFlow
1522  * connection if the switch processes the returned message correctly.  (If
1523  * '*next != want' then the caller will have to iterate.)
1524  *
1525  * If 'current == want', returns NULL and stores 'current' in '*next'. */
1526 struct ofpbuf *
1527 ofputil_encode_set_protocol(enum ofputil_protocol current,
1528                             enum ofputil_protocol want,
1529                             enum ofputil_protocol *next)
1530 {
1531     enum ofputil_protocol cur_base, want_base;
1532     bool cur_tid, want_tid;
1533
1534     cur_base = ofputil_protocol_to_base(current);
1535     want_base = ofputil_protocol_to_base(want);
1536     if (cur_base != want_base) {
1537         *next = ofputil_protocol_set_base(current, want_base);
1538
1539         switch (want_base) {
1540         case OFPUTIL_P_NXM:
1541             return ofputil_encode_nx_set_flow_format(NXFF_NXM);
1542
1543         case OFPUTIL_P_OF10:
1544             return ofputil_encode_nx_set_flow_format(NXFF_OPENFLOW10);
1545
1546         case OFPUTIL_P_OF10_TID:
1547         case OFPUTIL_P_NXM_TID:
1548             NOT_REACHED();
1549         }
1550     }
1551
1552     cur_tid = (current & OFPUTIL_P_TID) != 0;
1553     want_tid = (want & OFPUTIL_P_TID) != 0;
1554     if (cur_tid != want_tid) {
1555         *next = ofputil_protocol_set_tid(current, want_tid);
1556         return ofputil_make_flow_mod_table_id(want_tid);
1557     }
1558
1559     assert(current == want);
1560
1561     *next = current;
1562     return NULL;
1563 }
1564
1565 /* Returns an NXT_SET_FLOW_FORMAT message that can be used to set the flow
1566  * format to 'nxff'.  */
1567 struct ofpbuf *
1568 ofputil_encode_nx_set_flow_format(enum nx_flow_format nxff)
1569 {
1570     struct nx_set_flow_format *sff;
1571     struct ofpbuf *msg;
1572
1573     assert(ofputil_nx_flow_format_is_valid(nxff));
1574
1575     sff = make_nxmsg(sizeof *sff, NXT_SET_FLOW_FORMAT, &msg);
1576     sff->format = htonl(nxff);
1577
1578     return msg;
1579 }
1580
1581 /* Returns the base protocol if 'flow_format' is a valid NXFF_* value, false
1582  * otherwise. */
1583 enum ofputil_protocol
1584 ofputil_nx_flow_format_to_protocol(enum nx_flow_format flow_format)
1585 {
1586     switch (flow_format) {
1587     case NXFF_OPENFLOW10:
1588         return OFPUTIL_P_OF10;
1589
1590     case NXFF_NXM:
1591         return OFPUTIL_P_NXM;
1592
1593     default:
1594         return 0;
1595     }
1596 }
1597
1598 /* Returns true if 'flow_format' is a valid NXFF_* value, false otherwise. */
1599 bool
1600 ofputil_nx_flow_format_is_valid(enum nx_flow_format flow_format)
1601 {
1602     return ofputil_nx_flow_format_to_protocol(flow_format) != 0;
1603 }
1604
1605 /* Returns a string version of 'flow_format', which must be a valid NXFF_*
1606  * value. */
1607 const char *
1608 ofputil_nx_flow_format_to_string(enum nx_flow_format flow_format)
1609 {
1610     switch (flow_format) {
1611     case NXFF_OPENFLOW10:
1612         return "openflow10";
1613     case NXFF_NXM:
1614         return "nxm";
1615     default:
1616         NOT_REACHED();
1617     }
1618 }
1619
1620 struct ofpbuf *
1621 ofputil_make_set_packet_in_format(enum nx_packet_in_format packet_in_format)
1622 {
1623     struct nx_set_packet_in_format *spif;
1624     struct ofpbuf *msg;
1625
1626     spif = make_nxmsg(sizeof *spif, NXT_SET_PACKET_IN_FORMAT, &msg);
1627     spif->format = htonl(packet_in_format);
1628
1629     return msg;
1630 }
1631
1632 /* Returns an OpenFlow message that can be used to turn the flow_mod_table_id
1633  * extension on or off (according to 'flow_mod_table_id'). */
1634 struct ofpbuf *
1635 ofputil_make_flow_mod_table_id(bool flow_mod_table_id)
1636 {
1637     struct nx_flow_mod_table_id *nfmti;
1638     struct ofpbuf *msg;
1639
1640     nfmti = make_nxmsg(sizeof *nfmti, NXT_FLOW_MOD_TABLE_ID, &msg);
1641     nfmti->set = flow_mod_table_id;
1642     return msg;
1643 }
1644
1645 /* Converts an OFPT_FLOW_MOD or NXT_FLOW_MOD message 'oh' into an abstract
1646  * flow_mod in 'fm'.  Returns 0 if successful, otherwise an OpenFlow error
1647  * code.
1648  *
1649  * Uses 'ofpacts' to store the abstract OFPACT_* version of 'oh''s actions.
1650  * The caller must initialize 'ofpacts' and retains ownership of it.
1651  * 'fm->ofpacts' will point into the 'ofpacts' buffer.
1652  *
1653  * Does not validate the flow_mod actions.  The caller should do that, with
1654  * ofpacts_check(). */
1655 enum ofperr
1656 ofputil_decode_flow_mod(struct ofputil_flow_mod *fm,
1657                         const struct ofp_header *oh,
1658                         enum ofputil_protocol protocol,
1659                         struct ofpbuf *ofpacts)
1660 {
1661     const struct ofputil_msg_type *type;
1662     uint16_t command;
1663     struct ofpbuf b;
1664
1665     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1666
1667     ofputil_decode_msg_type(oh, &type);
1668     if (ofputil_msg_type_code(type) == OFPUTIL_OFPT_FLOW_MOD) {
1669         /* Standard OpenFlow flow_mod. */
1670         const struct ofp_flow_mod *ofm;
1671         uint16_t priority;
1672         enum ofperr error;
1673
1674         /* Get the ofp_flow_mod. */
1675         ofm = ofpbuf_pull(&b, sizeof *ofm);
1676
1677         /* Set priority based on original wildcards.  Normally we'd allow
1678          * ofputil_cls_rule_from_match() to do this for us, but
1679          * ofputil_normalize_rule() can put wildcards where the original flow
1680          * didn't have them. */
1681         priority = ntohs(ofm->priority);
1682         if (!(ofm->match.wildcards & htonl(OFPFW10_ALL))) {
1683             priority = UINT16_MAX;
1684         }
1685
1686         /* Translate the rule. */
1687         ofputil_cls_rule_from_ofp10_match(&ofm->match, priority, &fm->cr);
1688         ofputil_normalize_rule(&fm->cr);
1689
1690         /* Now get the actions. */
1691         error = ofpacts_pull_openflow10(&b, b.size, ofpacts);
1692         if (error) {
1693             return error;
1694         }
1695
1696         /* Translate the message. */
1697         command = ntohs(ofm->command);
1698         fm->cookie = htonll(0);
1699         fm->cookie_mask = htonll(0);
1700         fm->new_cookie = ofm->cookie;
1701         fm->idle_timeout = ntohs(ofm->idle_timeout);
1702         fm->hard_timeout = ntohs(ofm->hard_timeout);
1703         fm->buffer_id = ntohl(ofm->buffer_id);
1704         fm->out_port = ntohs(ofm->out_port);
1705         fm->flags = ntohs(ofm->flags);
1706     } else if (ofputil_msg_type_code(type) == OFPUTIL_NXT_FLOW_MOD) {
1707         /* Nicira extended flow_mod. */
1708         const struct nx_flow_mod *nfm;
1709         enum ofperr error;
1710
1711         /* Dissect the message. */
1712         nfm = ofpbuf_pull(&b, sizeof *nfm);
1713         error = nx_pull_match(&b, ntohs(nfm->match_len), ntohs(nfm->priority),
1714                               &fm->cr, &fm->cookie, &fm->cookie_mask);
1715         if (error) {
1716             return error;
1717         }
1718         error = ofpacts_pull_openflow10(&b, b.size, ofpacts);
1719         if (error) {
1720             return error;
1721         }
1722
1723         /* Translate the message. */
1724         command = ntohs(nfm->command);
1725         if ((command & 0xff) == OFPFC_ADD && fm->cookie_mask) {
1726             /* Flow additions may only set a new cookie, not match an
1727              * existing cookie. */
1728             return OFPERR_NXBRC_NXM_INVALID;
1729         }
1730         fm->new_cookie = nfm->cookie;
1731         fm->idle_timeout = ntohs(nfm->idle_timeout);
1732         fm->hard_timeout = ntohs(nfm->hard_timeout);
1733         fm->buffer_id = ntohl(nfm->buffer_id);
1734         fm->out_port = ntohs(nfm->out_port);
1735         fm->flags = ntohs(nfm->flags);
1736     } else {
1737         NOT_REACHED();
1738     }
1739
1740     fm->ofpacts = ofpacts->data;
1741     fm->ofpacts_len = ofpacts->size;
1742     if (protocol & OFPUTIL_P_TID) {
1743         fm->command = command & 0xff;
1744         fm->table_id = command >> 8;
1745     } else {
1746         fm->command = command;
1747         fm->table_id = 0xff;
1748     }
1749
1750     return 0;
1751 }
1752
1753 /* Converts 'fm' into an OFPT_FLOW_MOD or NXT_FLOW_MOD message according to
1754  * 'protocol' and returns the message. */
1755 struct ofpbuf *
1756 ofputil_encode_flow_mod(const struct ofputil_flow_mod *fm,
1757                         enum ofputil_protocol protocol)
1758 {
1759     struct ofp_flow_mod *ofm;
1760     struct nx_flow_mod *nfm;
1761     struct ofpbuf *msg;
1762     uint16_t command;
1763     int match_len;
1764
1765     command = (protocol & OFPUTIL_P_TID
1766                ? (fm->command & 0xff) | (fm->table_id << 8)
1767                : fm->command);
1768
1769     switch (protocol) {
1770     case OFPUTIL_P_OF10:
1771     case OFPUTIL_P_OF10_TID:
1772         msg = ofpbuf_new(sizeof *ofm + fm->ofpacts_len);
1773         ofm = put_openflow(sizeof *ofm, OFPT_FLOW_MOD, msg);
1774         ofputil_cls_rule_to_ofp10_match(&fm->cr, &ofm->match);
1775         ofm->cookie = fm->new_cookie;
1776         ofm->command = htons(command);
1777         ofm->idle_timeout = htons(fm->idle_timeout);
1778         ofm->hard_timeout = htons(fm->hard_timeout);
1779         ofm->priority = htons(fm->cr.priority);
1780         ofm->buffer_id = htonl(fm->buffer_id);
1781         ofm->out_port = htons(fm->out_port);
1782         ofm->flags = htons(fm->flags);
1783         break;
1784
1785     case OFPUTIL_P_NXM:
1786     case OFPUTIL_P_NXM_TID:
1787         msg = ofpbuf_new(sizeof *nfm + NXM_TYPICAL_LEN + fm->ofpacts_len);
1788         put_nxmsg(sizeof *nfm, NXT_FLOW_MOD, msg);
1789         nfm = msg->data;
1790         nfm->command = htons(command);
1791         nfm->cookie = fm->new_cookie;
1792         match_len = nx_put_match(msg, false, &fm->cr,
1793                                  fm->cookie, fm->cookie_mask);
1794         nfm = msg->data;
1795         nfm->idle_timeout = htons(fm->idle_timeout);
1796         nfm->hard_timeout = htons(fm->hard_timeout);
1797         nfm->priority = htons(fm->cr.priority);
1798         nfm->buffer_id = htonl(fm->buffer_id);
1799         nfm->out_port = htons(fm->out_port);
1800         nfm->flags = htons(fm->flags);
1801         nfm->match_len = htons(match_len);
1802         break;
1803
1804     default:
1805         NOT_REACHED();
1806     }
1807
1808     if (fm->ofpacts) {
1809         ofpacts_put_openflow10(fm->ofpacts, fm->ofpacts_len, msg);
1810     }
1811     update_openflow_length(msg);
1812     return msg;
1813 }
1814
1815 /* Returns a bitmask with a 1-bit for each protocol that could be used to
1816  * send all of the 'n_fm's flow table modification requests in 'fms', and a
1817  * 0-bit for each protocol that is inadequate.
1818  *
1819  * (The return value will have at least one 1-bit.) */
1820 enum ofputil_protocol
1821 ofputil_flow_mod_usable_protocols(const struct ofputil_flow_mod *fms,
1822                                   size_t n_fms)
1823 {
1824     enum ofputil_protocol usable_protocols;
1825     size_t i;
1826
1827     usable_protocols = OFPUTIL_P_ANY;
1828     for (i = 0; i < n_fms; i++) {
1829         const struct ofputil_flow_mod *fm = &fms[i];
1830
1831         usable_protocols &= ofputil_usable_protocols(&fm->cr);
1832         if (fm->table_id != 0xff) {
1833             usable_protocols &= OFPUTIL_P_TID;
1834         }
1835
1836         /* Matching of the cookie is only supported through NXM. */
1837         if (fm->cookie_mask != htonll(0)) {
1838             usable_protocols &= OFPUTIL_P_NXM_ANY;
1839         }
1840     }
1841     assert(usable_protocols);
1842
1843     return usable_protocols;
1844 }
1845
1846 static enum ofperr
1847 ofputil_decode_ofpst_flow_request(struct ofputil_flow_stats_request *fsr,
1848                                   const struct ofp_header *oh,
1849                                   bool aggregate)
1850 {
1851     const struct ofp_flow_stats_request *ofsr =
1852         (const struct ofp_flow_stats_request *) oh;
1853
1854     fsr->aggregate = aggregate;
1855     ofputil_cls_rule_from_ofp10_match(&ofsr->match, 0, &fsr->match);
1856     fsr->out_port = ntohs(ofsr->out_port);
1857     fsr->table_id = ofsr->table_id;
1858     fsr->cookie = fsr->cookie_mask = htonll(0);
1859
1860     return 0;
1861 }
1862
1863 static enum ofperr
1864 ofputil_decode_nxst_flow_request(struct ofputil_flow_stats_request *fsr,
1865                                  const struct ofp_header *oh,
1866                                  bool aggregate)
1867 {
1868     const struct nx_flow_stats_request *nfsr;
1869     struct ofpbuf b;
1870     enum ofperr error;
1871
1872     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1873
1874     nfsr = ofpbuf_pull(&b, sizeof *nfsr);
1875     error = nx_pull_match(&b, ntohs(nfsr->match_len), 0, &fsr->match,
1876                           &fsr->cookie, &fsr->cookie_mask);
1877     if (error) {
1878         return error;
1879     }
1880     if (b.size) {
1881         return OFPERR_OFPBRC_BAD_LEN;
1882     }
1883
1884     fsr->aggregate = aggregate;
1885     fsr->out_port = ntohs(nfsr->out_port);
1886     fsr->table_id = nfsr->table_id;
1887
1888     return 0;
1889 }
1890
1891 /* Converts an OFPST_FLOW, OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE
1892  * request 'oh', into an abstract flow_stats_request in 'fsr'.  Returns 0 if
1893  * successful, otherwise an OpenFlow error code. */
1894 enum ofperr
1895 ofputil_decode_flow_stats_request(struct ofputil_flow_stats_request *fsr,
1896                                   const struct ofp_header *oh)
1897 {
1898     const struct ofputil_msg_type *type;
1899     struct ofpbuf b;
1900     int code;
1901
1902     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1903
1904     ofputil_decode_msg_type(oh, &type);
1905     code = ofputil_msg_type_code(type);
1906     switch (code) {
1907     case OFPUTIL_OFPST_FLOW_REQUEST:
1908         return ofputil_decode_ofpst_flow_request(fsr, oh, false);
1909
1910     case OFPUTIL_OFPST_AGGREGATE_REQUEST:
1911         return ofputil_decode_ofpst_flow_request(fsr, oh, true);
1912
1913     case OFPUTIL_NXST_FLOW_REQUEST:
1914         return ofputil_decode_nxst_flow_request(fsr, oh, false);
1915
1916     case OFPUTIL_NXST_AGGREGATE_REQUEST:
1917         return ofputil_decode_nxst_flow_request(fsr, oh, true);
1918
1919     default:
1920         /* Hey, the caller lied. */
1921         NOT_REACHED();
1922     }
1923 }
1924
1925 /* Converts abstract flow_stats_request 'fsr' into an OFPST_FLOW,
1926  * OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE request 'oh' according to
1927  * 'protocol', and returns the message. */
1928 struct ofpbuf *
1929 ofputil_encode_flow_stats_request(const struct ofputil_flow_stats_request *fsr,
1930                                   enum ofputil_protocol protocol)
1931 {
1932     struct ofpbuf *msg;
1933
1934     switch (protocol) {
1935     case OFPUTIL_P_OF10:
1936     case OFPUTIL_P_OF10_TID: {
1937         struct ofp_flow_stats_request *ofsr;
1938         int type;
1939
1940         type = fsr->aggregate ? OFPST_AGGREGATE : OFPST_FLOW;
1941         ofsr = ofputil_make_stats_request(sizeof *ofsr, type, 0, &msg);
1942         ofputil_cls_rule_to_ofp10_match(&fsr->match, &ofsr->match);
1943         ofsr->table_id = fsr->table_id;
1944         ofsr->out_port = htons(fsr->out_port);
1945         break;
1946     }
1947
1948     case OFPUTIL_P_NXM:
1949     case OFPUTIL_P_NXM_TID: {
1950         struct nx_flow_stats_request *nfsr;
1951         int match_len;
1952         int subtype;
1953
1954         subtype = fsr->aggregate ? NXST_AGGREGATE : NXST_FLOW;
1955         ofputil_make_stats_request(sizeof *nfsr, OFPST_VENDOR, subtype, &msg);
1956         match_len = nx_put_match(msg, false, &fsr->match,
1957                                  fsr->cookie, fsr->cookie_mask);
1958
1959         nfsr = msg->data;
1960         nfsr->out_port = htons(fsr->out_port);
1961         nfsr->match_len = htons(match_len);
1962         nfsr->table_id = fsr->table_id;
1963         break;
1964     }
1965
1966     default:
1967         NOT_REACHED();
1968     }
1969
1970     return msg;
1971 }
1972
1973 /* Returns a bitmask with a 1-bit for each protocol that could be used to
1974  * accurately encode 'fsr', and a 0-bit for each protocol that is inadequate.
1975  *
1976  * (The return value will have at least one 1-bit.) */
1977 enum ofputil_protocol
1978 ofputil_flow_stats_request_usable_protocols(
1979     const struct ofputil_flow_stats_request *fsr)
1980 {
1981     enum ofputil_protocol usable_protocols;
1982
1983     usable_protocols = ofputil_usable_protocols(&fsr->match);
1984     if (fsr->cookie_mask != htonll(0)) {
1985         usable_protocols &= OFPUTIL_P_NXM_ANY;
1986     }
1987     return usable_protocols;
1988 }
1989
1990 /* Converts an OFPST_FLOW or NXST_FLOW reply in 'msg' into an abstract
1991  * ofputil_flow_stats in 'fs'.
1992  *
1993  * Multiple OFPST_FLOW or NXST_FLOW replies can be packed into a single
1994  * OpenFlow message.  Calling this function multiple times for a single 'msg'
1995  * iterates through the replies.  The caller must initially leave 'msg''s layer
1996  * pointers null and not modify them between calls.
1997  *
1998  * Most switches don't send the values needed to populate fs->idle_age and
1999  * fs->hard_age, so those members will usually be set to 0.  If the switch from
2000  * which 'msg' originated is known to implement NXT_FLOW_AGE, then pass
2001  * 'flow_age_extension' as true so that the contents of 'msg' determine the
2002  * 'idle_age' and 'hard_age' members in 'fs'.
2003  *
2004  * Uses 'ofpacts' to store the abstract OFPACT_* version of the flow stats
2005  * reply's actions.  The caller must initialize 'ofpacts' and retains ownership
2006  * of it.  'fs->ofpacts' will point into the 'ofpacts' buffer.
2007  *
2008  * Returns 0 if successful, EOF if no replies were left in this 'msg',
2009  * otherwise a positive errno value. */
2010 int
2011 ofputil_decode_flow_stats_reply(struct ofputil_flow_stats *fs,
2012                                 struct ofpbuf *msg,
2013                                 bool flow_age_extension,
2014                                 struct ofpbuf *ofpacts)
2015 {
2016     const struct ofputil_msg_type *type;
2017     int code;
2018
2019     ofputil_decode_msg_type(msg->l2 ? msg->l2 : msg->data, &type);
2020     code = ofputil_msg_type_code(type);
2021     if (!msg->l2) {
2022         msg->l2 = msg->data;
2023         if (code == OFPUTIL_OFPST_FLOW_REPLY) {
2024             ofpbuf_pull(msg, sizeof(struct ofp_stats_msg));
2025         } else if (code == OFPUTIL_NXST_FLOW_REPLY) {
2026             ofpbuf_pull(msg, sizeof(struct nicira_stats_msg));
2027         } else {
2028             NOT_REACHED();
2029         }
2030     }
2031
2032     if (!msg->size) {
2033         return EOF;
2034     } else if (code == OFPUTIL_OFPST_FLOW_REPLY) {
2035         const struct ofp_flow_stats *ofs;
2036         size_t length;
2037
2038         ofs = ofpbuf_try_pull(msg, sizeof *ofs);
2039         if (!ofs) {
2040             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply has %zu leftover "
2041                          "bytes at end", msg->size);
2042             return EINVAL;
2043         }
2044
2045         length = ntohs(ofs->length);
2046         if (length < sizeof *ofs) {
2047             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply claims invalid "
2048                          "length %zu", length);
2049             return EINVAL;
2050         }
2051
2052         if (ofpacts_pull_openflow10(msg, length - sizeof *ofs, ofpacts)) {
2053             return EINVAL;
2054         }
2055
2056         fs->cookie = get_32aligned_be64(&ofs->cookie);
2057         ofputil_cls_rule_from_ofp10_match(&ofs->match, ntohs(ofs->priority),
2058                                           &fs->rule);
2059         fs->table_id = ofs->table_id;
2060         fs->duration_sec = ntohl(ofs->duration_sec);
2061         fs->duration_nsec = ntohl(ofs->duration_nsec);
2062         fs->idle_timeout = ntohs(ofs->idle_timeout);
2063         fs->hard_timeout = ntohs(ofs->hard_timeout);
2064         fs->idle_age = -1;
2065         fs->hard_age = -1;
2066         fs->packet_count = ntohll(get_32aligned_be64(&ofs->packet_count));
2067         fs->byte_count = ntohll(get_32aligned_be64(&ofs->byte_count));
2068     } else if (code == OFPUTIL_NXST_FLOW_REPLY) {
2069         const struct nx_flow_stats *nfs;
2070         size_t match_len, actions_len, length;
2071
2072         nfs = ofpbuf_try_pull(msg, sizeof *nfs);
2073         if (!nfs) {
2074             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply has %zu leftover "
2075                          "bytes at end", msg->size);
2076             return EINVAL;
2077         }
2078
2079         length = ntohs(nfs->length);
2080         match_len = ntohs(nfs->match_len);
2081         if (length < sizeof *nfs + ROUND_UP(match_len, 8)) {
2082             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply with match_len=%zu "
2083                          "claims invalid length %zu", match_len, length);
2084             return EINVAL;
2085         }
2086         if (nx_pull_match(msg, match_len, ntohs(nfs->priority), &fs->rule,
2087                           NULL, NULL)) {
2088             return EINVAL;
2089         }
2090
2091         actions_len = length - sizeof *nfs - ROUND_UP(match_len, 8);
2092         if (ofpacts_pull_openflow10(msg, actions_len, ofpacts)) {
2093             return EINVAL;
2094         }
2095
2096         fs->cookie = nfs->cookie;
2097         fs->table_id = nfs->table_id;
2098         fs->duration_sec = ntohl(nfs->duration_sec);
2099         fs->duration_nsec = ntohl(nfs->duration_nsec);
2100         fs->idle_timeout = ntohs(nfs->idle_timeout);
2101         fs->hard_timeout = ntohs(nfs->hard_timeout);
2102         fs->idle_age = -1;
2103         fs->hard_age = -1;
2104         if (flow_age_extension) {
2105             if (nfs->idle_age) {
2106                 fs->idle_age = ntohs(nfs->idle_age) - 1;
2107             }
2108             if (nfs->hard_age) {
2109                 fs->hard_age = ntohs(nfs->hard_age) - 1;
2110             }
2111         }
2112         fs->packet_count = ntohll(nfs->packet_count);
2113         fs->byte_count = ntohll(nfs->byte_count);
2114     } else {
2115         NOT_REACHED();
2116     }
2117
2118     fs->ofpacts = ofpacts->data;
2119     fs->ofpacts_len = ofpacts->size;
2120
2121     return 0;
2122 }
2123
2124 /* Returns 'count' unchanged except that UINT64_MAX becomes 0.
2125  *
2126  * We use this in situations where OVS internally uses UINT64_MAX to mean
2127  * "value unknown" but OpenFlow 1.0 does not define any unknown value. */
2128 static uint64_t
2129 unknown_to_zero(uint64_t count)
2130 {
2131     return count != UINT64_MAX ? count : 0;
2132 }
2133
2134 /* Appends an OFPST_FLOW or NXST_FLOW reply that contains the data in 'fs' to
2135  * those already present in the list of ofpbufs in 'replies'.  'replies' should
2136  * have been initialized with ofputil_start_stats_reply(). */
2137 void
2138 ofputil_append_flow_stats_reply(const struct ofputil_flow_stats *fs,
2139                                 struct list *replies)
2140 {
2141     struct ofpbuf *reply = ofpbuf_from_list(list_back(replies));
2142     const struct ofp_stats_msg *osm = reply->data;
2143     size_t start_ofs = reply->size;
2144
2145     if (osm->type == htons(OFPST_FLOW)) {
2146         struct ofp_flow_stats *ofs;
2147
2148         ofs = ofpbuf_put_uninit(reply, sizeof *ofs);
2149         ofs->table_id = fs->table_id;
2150         ofs->pad = 0;
2151         ofputil_cls_rule_to_ofp10_match(&fs->rule, &ofs->match);
2152         ofs->duration_sec = htonl(fs->duration_sec);
2153         ofs->duration_nsec = htonl(fs->duration_nsec);
2154         ofs->priority = htons(fs->rule.priority);
2155         ofs->idle_timeout = htons(fs->idle_timeout);
2156         ofs->hard_timeout = htons(fs->hard_timeout);
2157         memset(ofs->pad2, 0, sizeof ofs->pad2);
2158         put_32aligned_be64(&ofs->cookie, fs->cookie);
2159         put_32aligned_be64(&ofs->packet_count,
2160                            htonll(unknown_to_zero(fs->packet_count)));
2161         put_32aligned_be64(&ofs->byte_count,
2162                            htonll(unknown_to_zero(fs->byte_count)));
2163         ofpacts_put_openflow10(fs->ofpacts, fs->ofpacts_len, reply);
2164
2165         ofs = ofpbuf_at_assert(reply, start_ofs, sizeof *ofs);
2166         ofs->length = htons(reply->size - start_ofs);
2167     } else if (osm->type == htons(OFPST_VENDOR)) {
2168         struct nx_flow_stats *nfs;
2169
2170         nfs = ofpbuf_put_uninit(reply, sizeof *nfs);
2171         nfs->table_id = fs->table_id;
2172         nfs->pad = 0;
2173         nfs->duration_sec = htonl(fs->duration_sec);
2174         nfs->duration_nsec = htonl(fs->duration_nsec);
2175         nfs->priority = htons(fs->rule.priority);
2176         nfs->idle_timeout = htons(fs->idle_timeout);
2177         nfs->hard_timeout = htons(fs->hard_timeout);
2178         nfs->idle_age = htons(fs->idle_age < 0 ? 0
2179                               : fs->idle_age < UINT16_MAX ? fs->idle_age + 1
2180                               : UINT16_MAX);
2181         nfs->hard_age = htons(fs->hard_age < 0 ? 0
2182                               : fs->hard_age < UINT16_MAX ? fs->hard_age + 1
2183                               : UINT16_MAX);
2184         nfs->match_len = htons(nx_put_match(reply, false, &fs->rule, 0, 0));
2185         nfs->cookie = fs->cookie;
2186         nfs->packet_count = htonll(fs->packet_count);
2187         nfs->byte_count = htonll(fs->byte_count);
2188         ofpacts_put_openflow10(fs->ofpacts, fs->ofpacts_len, reply);
2189
2190         nfs = ofpbuf_at_assert(reply, start_ofs, sizeof *nfs);
2191         nfs->length = htons(reply->size - start_ofs);
2192     } else {
2193         NOT_REACHED();
2194     }
2195
2196     ofputil_postappend_stats_reply(start_ofs, replies);
2197 }
2198
2199 /* Converts abstract ofputil_aggregate_stats 'stats' into an OFPST_AGGREGATE or
2200  * NXST_AGGREGATE reply according to 'protocol', and returns the message. */
2201 struct ofpbuf *
2202 ofputil_encode_aggregate_stats_reply(
2203     const struct ofputil_aggregate_stats *stats,
2204     const struct ofp_stats_msg *request)
2205 {
2206     struct ofpbuf *msg;
2207
2208     if (request->type == htons(OFPST_AGGREGATE)) {
2209         struct ofp_aggregate_stats_reply *asr;
2210
2211         asr = ofputil_make_stats_reply(sizeof *asr, request, &msg);
2212         put_32aligned_be64(&asr->packet_count,
2213                            htonll(unknown_to_zero(stats->packet_count)));
2214         put_32aligned_be64(&asr->byte_count,
2215                            htonll(unknown_to_zero(stats->byte_count)));
2216         asr->flow_count = htonl(stats->flow_count);
2217     } else if (request->type == htons(OFPST_VENDOR)) {
2218         struct nx_aggregate_stats_reply *nasr;
2219
2220         nasr = ofputil_make_stats_reply(sizeof *nasr, request, &msg);
2221         assert(nasr->nsm.subtype == htonl(NXST_AGGREGATE));
2222         nasr->packet_count = htonll(stats->packet_count);
2223         nasr->byte_count = htonll(stats->byte_count);
2224         nasr->flow_count = htonl(stats->flow_count);
2225     } else {
2226         NOT_REACHED();
2227     }
2228
2229     return msg;
2230 }
2231
2232 /* Converts an OFPT_FLOW_REMOVED or NXT_FLOW_REMOVED message 'oh' into an
2233  * abstract ofputil_flow_removed in 'fr'.  Returns 0 if successful, otherwise
2234  * an OpenFlow error code. */
2235 enum ofperr
2236 ofputil_decode_flow_removed(struct ofputil_flow_removed *fr,
2237                             const struct ofp_header *oh)
2238 {
2239     const struct ofputil_msg_type *type;
2240     enum ofputil_msg_code code;
2241
2242     ofputil_decode_msg_type(oh, &type);
2243     code = ofputil_msg_type_code(type);
2244     if (code == OFPUTIL_OFPT_FLOW_REMOVED) {
2245         const struct ofp_flow_removed *ofr;
2246
2247         ofr = (const struct ofp_flow_removed *) oh;
2248         ofputil_cls_rule_from_ofp10_match(&ofr->match, ntohs(ofr->priority),
2249                                           &fr->rule);
2250         fr->cookie = ofr->cookie;
2251         fr->reason = ofr->reason;
2252         fr->duration_sec = ntohl(ofr->duration_sec);
2253         fr->duration_nsec = ntohl(ofr->duration_nsec);
2254         fr->idle_timeout = ntohs(ofr->idle_timeout);
2255         fr->packet_count = ntohll(ofr->packet_count);
2256         fr->byte_count = ntohll(ofr->byte_count);
2257     } else if (code == OFPUTIL_NXT_FLOW_REMOVED) {
2258         struct nx_flow_removed *nfr;
2259         struct ofpbuf b;
2260         int error;
2261
2262         ofpbuf_use_const(&b, oh, ntohs(oh->length));
2263
2264         nfr = ofpbuf_pull(&b, sizeof *nfr);
2265         error = nx_pull_match(&b, ntohs(nfr->match_len), ntohs(nfr->priority),
2266                               &fr->rule, NULL, NULL);
2267         if (error) {
2268             return error;
2269         }
2270         if (b.size) {
2271             return OFPERR_OFPBRC_BAD_LEN;
2272         }
2273
2274         fr->cookie = nfr->cookie;
2275         fr->reason = nfr->reason;
2276         fr->duration_sec = ntohl(nfr->duration_sec);
2277         fr->duration_nsec = ntohl(nfr->duration_nsec);
2278         fr->idle_timeout = ntohs(nfr->idle_timeout);
2279         fr->packet_count = ntohll(nfr->packet_count);
2280         fr->byte_count = ntohll(nfr->byte_count);
2281     } else {
2282         NOT_REACHED();
2283     }
2284
2285     return 0;
2286 }
2287
2288 /* Converts abstract ofputil_flow_removed 'fr' into an OFPT_FLOW_REMOVED or
2289  * NXT_FLOW_REMOVED message 'oh' according to 'protocol', and returns the
2290  * message. */
2291 struct ofpbuf *
2292 ofputil_encode_flow_removed(const struct ofputil_flow_removed *fr,
2293                             enum ofputil_protocol protocol)
2294 {
2295     struct ofpbuf *msg;
2296
2297     switch (protocol) {
2298     case OFPUTIL_P_OF10:
2299     case OFPUTIL_P_OF10_TID: {
2300         struct ofp_flow_removed *ofr;
2301
2302         ofr = make_openflow_xid(sizeof *ofr, OFPT_FLOW_REMOVED, htonl(0),
2303                                 &msg);
2304         ofputil_cls_rule_to_ofp10_match(&fr->rule, &ofr->match);
2305         ofr->cookie = fr->cookie;
2306         ofr->priority = htons(fr->rule.priority);
2307         ofr->reason = fr->reason;
2308         ofr->duration_sec = htonl(fr->duration_sec);
2309         ofr->duration_nsec = htonl(fr->duration_nsec);
2310         ofr->idle_timeout = htons(fr->idle_timeout);
2311         ofr->packet_count = htonll(unknown_to_zero(fr->packet_count));
2312         ofr->byte_count = htonll(unknown_to_zero(fr->byte_count));
2313         break;
2314     }
2315
2316     case OFPUTIL_P_NXM:
2317     case OFPUTIL_P_NXM_TID: {
2318         struct nx_flow_removed *nfr;
2319         int match_len;
2320
2321         make_nxmsg_xid(sizeof *nfr, NXT_FLOW_REMOVED, htonl(0), &msg);
2322         match_len = nx_put_match(msg, false, &fr->rule, 0, 0);
2323
2324         nfr = msg->data;
2325         nfr->cookie = fr->cookie;
2326         nfr->priority = htons(fr->rule.priority);
2327         nfr->reason = fr->reason;
2328         nfr->duration_sec = htonl(fr->duration_sec);
2329         nfr->duration_nsec = htonl(fr->duration_nsec);
2330         nfr->idle_timeout = htons(fr->idle_timeout);
2331         nfr->match_len = htons(match_len);
2332         nfr->packet_count = htonll(fr->packet_count);
2333         nfr->byte_count = htonll(fr->byte_count);
2334         break;
2335     }
2336
2337     default:
2338         NOT_REACHED();
2339     }
2340
2341     return msg;
2342 }
2343
2344 enum ofperr
2345 ofputil_decode_packet_in(struct ofputil_packet_in *pin,
2346                          const struct ofp_header *oh)
2347 {
2348     const struct ofputil_msg_type *type;
2349     enum ofputil_msg_code code;
2350
2351     ofputil_decode_msg_type(oh, &type);
2352     code = ofputil_msg_type_code(type);
2353     memset(pin, 0, sizeof *pin);
2354
2355     if (code == OFPUTIL_OFPT_PACKET_IN) {
2356         const struct ofp_packet_in *opi = (const struct ofp_packet_in *) oh;
2357
2358         pin->packet = opi->data;
2359         pin->packet_len = ntohs(opi->header.length)
2360             - offsetof(struct ofp_packet_in, data);
2361
2362         pin->fmd.in_port = ntohs(opi->in_port);
2363         pin->reason = opi->reason;
2364         pin->buffer_id = ntohl(opi->buffer_id);
2365         pin->total_len = ntohs(opi->total_len);
2366     } else if (code == OFPUTIL_NXT_PACKET_IN) {
2367         const struct nx_packet_in *npi;
2368         struct cls_rule rule;
2369         struct ofpbuf b;
2370         int error;
2371
2372         ofpbuf_use_const(&b, oh, ntohs(oh->length));
2373
2374         npi = ofpbuf_pull(&b, sizeof *npi);
2375         error = nx_pull_match_loose(&b, ntohs(npi->match_len), 0, &rule, NULL,
2376                                     NULL);
2377         if (error) {
2378             return error;
2379         }
2380
2381         if (!ofpbuf_try_pull(&b, 2)) {
2382             return OFPERR_OFPBRC_BAD_LEN;
2383         }
2384
2385         pin->packet = b.data;
2386         pin->packet_len = b.size;
2387         pin->reason = npi->reason;
2388         pin->table_id = npi->table_id;
2389         pin->cookie = npi->cookie;
2390
2391         pin->fmd.in_port = rule.flow.in_port;
2392
2393         pin->fmd.tun_id = rule.flow.tun_id;
2394         pin->fmd.tun_id_mask = rule.wc.tun_id_mask;
2395
2396         pin->fmd.metadata = rule.flow.metadata;
2397         pin->fmd.metadata_mask = rule.wc.metadata_mask;
2398
2399         memcpy(pin->fmd.regs, rule.flow.regs, sizeof pin->fmd.regs);
2400         memcpy(pin->fmd.reg_masks, rule.wc.reg_masks,
2401                sizeof pin->fmd.reg_masks);
2402
2403         pin->buffer_id = ntohl(npi->buffer_id);
2404         pin->total_len = ntohs(npi->total_len);
2405     } else {
2406         NOT_REACHED();
2407     }
2408
2409     return 0;
2410 }
2411
2412 /* Converts abstract ofputil_packet_in 'pin' into a PACKET_IN message
2413  * in the format specified by 'packet_in_format'.  */
2414 struct ofpbuf *
2415 ofputil_encode_packet_in(const struct ofputil_packet_in *pin,
2416                          enum nx_packet_in_format packet_in_format)
2417 {
2418     size_t send_len = MIN(pin->send_len, pin->packet_len);
2419     struct ofpbuf *packet;
2420
2421     /* Add OFPT_PACKET_IN. */
2422     if (packet_in_format == NXPIF_OPENFLOW10) {
2423         size_t header_len = offsetof(struct ofp_packet_in, data);
2424         struct ofp_packet_in *opi;
2425
2426         packet = ofpbuf_new(send_len + header_len);
2427         opi = ofpbuf_put_zeros(packet, header_len);
2428         opi->header.version = OFP10_VERSION;
2429         opi->header.type = OFPT_PACKET_IN;
2430         opi->total_len = htons(pin->total_len);
2431         opi->in_port = htons(pin->fmd.in_port);
2432         opi->reason = pin->reason;
2433         opi->buffer_id = htonl(pin->buffer_id);
2434
2435         ofpbuf_put(packet, pin->packet, send_len);
2436     } else if (packet_in_format == NXPIF_NXM) {
2437         struct nx_packet_in *npi;
2438         struct cls_rule rule;
2439         size_t match_len;
2440         size_t i;
2441
2442         /* Estimate of required PACKET_IN length includes the NPI header, space
2443          * for the match (2 times sizeof the metadata seems like enough), 2
2444          * bytes for padding, and the packet length. */
2445         packet = ofpbuf_new(sizeof *npi + sizeof(struct flow_metadata) * 2
2446                             + 2 + send_len);
2447
2448         cls_rule_init_catchall(&rule, 0);
2449         cls_rule_set_tun_id_masked(&rule, pin->fmd.tun_id,
2450                                    pin->fmd.tun_id_mask);
2451         cls_rule_set_metadata_masked(&rule, pin->fmd.metadata,
2452                                    pin->fmd.metadata_mask);
2453
2454
2455         for (i = 0; i < FLOW_N_REGS; i++) {
2456             cls_rule_set_reg_masked(&rule, i, pin->fmd.regs[i],
2457                                     pin->fmd.reg_masks[i]);
2458         }
2459
2460         cls_rule_set_in_port(&rule, pin->fmd.in_port);
2461
2462         ofpbuf_put_zeros(packet, sizeof *npi);
2463         match_len = nx_put_match(packet, false, &rule, 0, 0);
2464         ofpbuf_put_zeros(packet, 2);
2465         ofpbuf_put(packet, pin->packet, send_len);
2466
2467         npi = packet->data;
2468         npi->nxh.header.version = OFP10_VERSION;
2469         npi->nxh.header.type = OFPT_VENDOR;
2470         npi->nxh.vendor = htonl(NX_VENDOR_ID);
2471         npi->nxh.subtype = htonl(NXT_PACKET_IN);
2472
2473         npi->buffer_id = htonl(pin->buffer_id);
2474         npi->total_len = htons(pin->total_len);
2475         npi->reason = pin->reason;
2476         npi->table_id = pin->table_id;
2477         npi->cookie = pin->cookie;
2478         npi->match_len = htons(match_len);
2479     } else {
2480         NOT_REACHED();
2481     }
2482     update_openflow_length(packet);
2483
2484     return packet;
2485 }
2486
2487 const char *
2488 ofputil_packet_in_reason_to_string(enum ofp_packet_in_reason reason)
2489 {
2490     static char s[INT_STRLEN(int) + 1];
2491
2492     switch (reason) {
2493     case OFPR_NO_MATCH:
2494         return "no_match";
2495     case OFPR_ACTION:
2496         return "action";
2497     case OFPR_INVALID_TTL:
2498         return "invalid_ttl";
2499
2500     case OFPR_N_REASONS:
2501     default:
2502         sprintf(s, "%d", (int) reason);
2503         return s;
2504     }
2505 }
2506
2507 bool
2508 ofputil_packet_in_reason_from_string(const char *s,
2509                                      enum ofp_packet_in_reason *reason)
2510 {
2511     int i;
2512
2513     for (i = 0; i < OFPR_N_REASONS; i++) {
2514         if (!strcasecmp(s, ofputil_packet_in_reason_to_string(i))) {
2515             *reason = i;
2516             return true;
2517         }
2518     }
2519     return false;
2520 }
2521
2522 /* Converts an OFPT_PACKET_OUT in 'opo' into an abstract ofputil_packet_out in
2523  * 'po'.
2524  *
2525  * Uses 'ofpacts' to store the abstract OFPACT_* version of the packet out
2526  * message's actions.  The caller must initialize 'ofpacts' and retains
2527  * ownership of it.  'po->ofpacts' will point into the 'ofpacts' buffer.
2528  *
2529  * Returns 0 if successful, otherwise an OFPERR_* value. */
2530 enum ofperr
2531 ofputil_decode_packet_out(struct ofputil_packet_out *po,
2532                           const struct ofp_packet_out *opo,
2533                           struct ofpbuf *ofpacts)
2534 {
2535     enum ofperr error;
2536     struct ofpbuf b;
2537
2538     po->buffer_id = ntohl(opo->buffer_id);
2539     po->in_port = ntohs(opo->in_port);
2540     if (po->in_port >= OFPP_MAX && po->in_port != OFPP_LOCAL
2541         && po->in_port != OFPP_NONE && po->in_port != OFPP_CONTROLLER) {
2542         VLOG_WARN_RL(&bad_ofmsg_rl, "packet-out has bad input port %#"PRIx16,
2543                      po->in_port);
2544         return OFPERR_NXBRC_BAD_IN_PORT;
2545     }
2546
2547     ofpbuf_use_const(&b, opo, ntohs(opo->header.length));
2548     ofpbuf_pull(&b, sizeof *opo);
2549
2550     error = ofpacts_pull_openflow10(&b, ntohs(opo->actions_len), ofpacts);
2551     if (error) {
2552         return error;
2553     }
2554     po->ofpacts = ofpacts->data;
2555     po->ofpacts_len = ofpacts->size;
2556
2557     if (po->buffer_id == UINT32_MAX) {
2558         po->packet = b.data;
2559         po->packet_len = b.size;
2560     } else {
2561         po->packet = NULL;
2562         po->packet_len = 0;
2563     }
2564
2565     return 0;
2566 }
2567 \f
2568 /* ofputil_phy_port */
2569
2570 /* NETDEV_F_* to and from OFPPF_* and OFPPF10_*. */
2571 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_HD    == OFPPF_10MB_HD);  /* bit 0 */
2572 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_FD    == OFPPF_10MB_FD);  /* bit 1 */
2573 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_HD   == OFPPF_100MB_HD); /* bit 2 */
2574 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_FD   == OFPPF_100MB_FD); /* bit 3 */
2575 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_HD     == OFPPF_1GB_HD);   /* bit 4 */
2576 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_FD     == OFPPF_1GB_FD);   /* bit 5 */
2577 BUILD_ASSERT_DECL((int) NETDEV_F_10GB_FD    == OFPPF_10GB_FD);  /* bit 6 */
2578
2579 /* NETDEV_F_ bits 11...15 are OFPPF10_ bits 7...11: */
2580 BUILD_ASSERT_DECL((int) NETDEV_F_COPPER == (OFPPF10_COPPER << 4));
2581 BUILD_ASSERT_DECL((int) NETDEV_F_FIBER == (OFPPF10_FIBER << 4));
2582 BUILD_ASSERT_DECL((int) NETDEV_F_AUTONEG == (OFPPF10_AUTONEG << 4));
2583 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE == (OFPPF10_PAUSE << 4));
2584 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE_ASYM == (OFPPF10_PAUSE_ASYM << 4));
2585
2586 static enum netdev_features
2587 netdev_port_features_from_ofp10(ovs_be32 ofp10_)
2588 {
2589     uint32_t ofp10 = ntohl(ofp10_);
2590     return (ofp10 & 0x7f) | ((ofp10 & 0xf80) << 4);
2591 }
2592
2593 static ovs_be32
2594 netdev_port_features_to_ofp10(enum netdev_features features)
2595 {
2596     return htonl((features & 0x7f) | ((features & 0xf800) >> 4));
2597 }
2598
2599 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_HD    == OFPPF_10MB_HD);     /* bit 0 */
2600 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_FD    == OFPPF_10MB_FD);     /* bit 1 */
2601 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_HD   == OFPPF_100MB_HD);    /* bit 2 */
2602 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_FD   == OFPPF_100MB_FD);    /* bit 3 */
2603 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_HD     == OFPPF_1GB_HD);      /* bit 4 */
2604 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_FD     == OFPPF_1GB_FD);      /* bit 5 */
2605 BUILD_ASSERT_DECL((int) NETDEV_F_10GB_FD    == OFPPF_10GB_FD);     /* bit 6 */
2606 BUILD_ASSERT_DECL((int) NETDEV_F_40GB_FD    == OFPPF11_40GB_FD);   /* bit 7 */
2607 BUILD_ASSERT_DECL((int) NETDEV_F_100GB_FD   == OFPPF11_100GB_FD);  /* bit 8 */
2608 BUILD_ASSERT_DECL((int) NETDEV_F_1TB_FD     == OFPPF11_1TB_FD);    /* bit 9 */
2609 BUILD_ASSERT_DECL((int) NETDEV_F_OTHER      == OFPPF11_OTHER);     /* bit 10 */
2610 BUILD_ASSERT_DECL((int) NETDEV_F_COPPER     == OFPPF11_COPPER);    /* bit 11 */
2611 BUILD_ASSERT_DECL((int) NETDEV_F_FIBER      == OFPPF11_FIBER);     /* bit 12 */
2612 BUILD_ASSERT_DECL((int) NETDEV_F_AUTONEG    == OFPPF11_AUTONEG);   /* bit 13 */
2613 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE      == OFPPF11_PAUSE);     /* bit 14 */
2614 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE_ASYM == OFPPF11_PAUSE_ASYM);/* bit 15 */
2615
2616 static enum netdev_features
2617 netdev_port_features_from_ofp11(ovs_be32 ofp11)
2618 {
2619     return ntohl(ofp11) & 0xffff;
2620 }
2621
2622 static ovs_be32
2623 netdev_port_features_to_ofp11(enum netdev_features features)
2624 {
2625     return htonl(features & 0xffff);
2626 }
2627
2628 static enum ofperr
2629 ofputil_decode_ofp10_phy_port(struct ofputil_phy_port *pp,
2630                               const struct ofp10_phy_port *opp)
2631 {
2632     memset(pp, 0, sizeof *pp);
2633
2634     pp->port_no = ntohs(opp->port_no);
2635     memcpy(pp->hw_addr, opp->hw_addr, OFP_ETH_ALEN);
2636     ovs_strlcpy(pp->name, opp->name, OFP_MAX_PORT_NAME_LEN);
2637
2638     pp->config = ntohl(opp->config) & OFPPC10_ALL;
2639     pp->state = ntohl(opp->state) & OFPPS10_ALL;
2640
2641     pp->curr = netdev_port_features_from_ofp10(opp->curr);
2642     pp->advertised = netdev_port_features_from_ofp10(opp->advertised);
2643     pp->supported = netdev_port_features_from_ofp10(opp->supported);
2644     pp->peer = netdev_port_features_from_ofp10(opp->peer);
2645
2646     pp->curr_speed = netdev_features_to_bps(pp->curr) / 1000;
2647     pp->max_speed = netdev_features_to_bps(pp->supported) / 1000;
2648
2649     return 0;
2650 }
2651
2652 static enum ofperr
2653 ofputil_decode_ofp11_port(struct ofputil_phy_port *pp,
2654                           const struct ofp11_port *op)
2655 {
2656     enum ofperr error;
2657
2658     memset(pp, 0, sizeof *pp);
2659
2660     error = ofputil_port_from_ofp11(op->port_no, &pp->port_no);
2661     if (error) {
2662         return error;
2663     }
2664     memcpy(pp->hw_addr, op->hw_addr, OFP_ETH_ALEN);
2665     ovs_strlcpy(pp->name, op->name, OFP_MAX_PORT_NAME_LEN);
2666
2667     pp->config = ntohl(op->config) & OFPPC11_ALL;
2668     pp->state = ntohl(op->state) & OFPPC11_ALL;
2669
2670     pp->curr = netdev_port_features_from_ofp11(op->curr);
2671     pp->advertised = netdev_port_features_from_ofp11(op->advertised);
2672     pp->supported = netdev_port_features_from_ofp11(op->supported);
2673     pp->peer = netdev_port_features_from_ofp11(op->peer);
2674
2675     pp->curr_speed = ntohl(op->curr_speed);
2676     pp->max_speed = ntohl(op->max_speed);
2677
2678     return 0;
2679 }
2680
2681 static size_t
2682 ofputil_get_phy_port_size(uint8_t ofp_version)
2683 {
2684     return ofp_version == OFP10_VERSION ? sizeof(struct ofp10_phy_port)
2685                                         : sizeof(struct ofp11_port);
2686 }
2687
2688 static void
2689 ofputil_encode_ofp10_phy_port(const struct ofputil_phy_port *pp,
2690                               struct ofp10_phy_port *opp)
2691 {
2692     memset(opp, 0, sizeof *opp);
2693
2694     opp->port_no = htons(pp->port_no);
2695     memcpy(opp->hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2696     ovs_strlcpy(opp->name, pp->name, OFP_MAX_PORT_NAME_LEN);
2697
2698     opp->config = htonl(pp->config & OFPPC10_ALL);
2699     opp->state = htonl(pp->state & OFPPS10_ALL);
2700
2701     opp->curr = netdev_port_features_to_ofp10(pp->curr);
2702     opp->advertised = netdev_port_features_to_ofp10(pp->advertised);
2703     opp->supported = netdev_port_features_to_ofp10(pp->supported);
2704     opp->peer = netdev_port_features_to_ofp10(pp->peer);
2705 }
2706
2707 static void
2708 ofputil_encode_ofp11_port(const struct ofputil_phy_port *pp,
2709                           struct ofp11_port *op)
2710 {
2711     memset(op, 0, sizeof *op);
2712
2713     op->port_no = ofputil_port_to_ofp11(pp->port_no);
2714     memcpy(op->hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2715     ovs_strlcpy(op->name, pp->name, OFP_MAX_PORT_NAME_LEN);
2716
2717     op->config = htonl(pp->config & OFPPC11_ALL);
2718     op->state = htonl(pp->state & OFPPS11_ALL);
2719
2720     op->curr = netdev_port_features_to_ofp11(pp->curr);
2721     op->advertised = netdev_port_features_to_ofp11(pp->advertised);
2722     op->supported = netdev_port_features_to_ofp11(pp->supported);
2723     op->peer = netdev_port_features_to_ofp11(pp->peer);
2724
2725     op->curr_speed = htonl(pp->curr_speed);
2726     op->max_speed = htonl(pp->max_speed);
2727 }
2728
2729 static void
2730 ofputil_put_phy_port(uint8_t ofp_version, const struct ofputil_phy_port *pp,
2731                      struct ofpbuf *b)
2732 {
2733     if (ofp_version == OFP10_VERSION) {
2734         struct ofp10_phy_port *opp;
2735         if (b->size + sizeof *opp <= UINT16_MAX) {
2736             opp = ofpbuf_put_uninit(b, sizeof *opp);
2737             ofputil_encode_ofp10_phy_port(pp, opp);
2738         }
2739     } else {
2740         struct ofp11_port *op;
2741         if (b->size + sizeof *op <= UINT16_MAX) {
2742             op = ofpbuf_put_uninit(b, sizeof *op);
2743             ofputil_encode_ofp11_port(pp, op);
2744         }
2745     }
2746 }
2747
2748 void
2749 ofputil_append_port_desc_stats_reply(uint8_t ofp_version,
2750                                      const struct ofputil_phy_port *pp,
2751                                      struct list *replies)
2752 {
2753     if (ofp_version == OFP10_VERSION) {
2754         struct ofp10_phy_port *opp;
2755
2756         opp = ofputil_append_stats_reply(sizeof *opp, replies);
2757         ofputil_encode_ofp10_phy_port(pp, opp);
2758     } else {
2759         struct ofp11_port *op;
2760
2761         op = ofputil_append_stats_reply(sizeof *op, replies);
2762         ofputil_encode_ofp11_port(pp, op);
2763     }
2764 }
2765 \f
2766 /* ofputil_switch_features */
2767
2768 #define OFPC_COMMON (OFPC_FLOW_STATS | OFPC_TABLE_STATS | OFPC_PORT_STATS | \
2769                      OFPC_IP_REASM | OFPC_QUEUE_STATS | OFPC_ARP_MATCH_IP)
2770 BUILD_ASSERT_DECL((int) OFPUTIL_C_FLOW_STATS == OFPC_FLOW_STATS);
2771 BUILD_ASSERT_DECL((int) OFPUTIL_C_TABLE_STATS == OFPC_TABLE_STATS);
2772 BUILD_ASSERT_DECL((int) OFPUTIL_C_PORT_STATS == OFPC_PORT_STATS);
2773 BUILD_ASSERT_DECL((int) OFPUTIL_C_IP_REASM == OFPC_IP_REASM);
2774 BUILD_ASSERT_DECL((int) OFPUTIL_C_QUEUE_STATS == OFPC_QUEUE_STATS);
2775 BUILD_ASSERT_DECL((int) OFPUTIL_C_ARP_MATCH_IP == OFPC_ARP_MATCH_IP);
2776
2777 struct ofputil_action_bit_translation {
2778     enum ofputil_action_bitmap ofputil_bit;
2779     int of_bit;
2780 };
2781
2782 static const struct ofputil_action_bit_translation of10_action_bits[] = {
2783     { OFPUTIL_A_OUTPUT,       OFPAT10_OUTPUT },
2784     { OFPUTIL_A_SET_VLAN_VID, OFPAT10_SET_VLAN_VID },
2785     { OFPUTIL_A_SET_VLAN_PCP, OFPAT10_SET_VLAN_PCP },
2786     { OFPUTIL_A_STRIP_VLAN,   OFPAT10_STRIP_VLAN },
2787     { OFPUTIL_A_SET_DL_SRC,   OFPAT10_SET_DL_SRC },
2788     { OFPUTIL_A_SET_DL_DST,   OFPAT10_SET_DL_DST },
2789     { OFPUTIL_A_SET_NW_SRC,   OFPAT10_SET_NW_SRC },
2790     { OFPUTIL_A_SET_NW_DST,   OFPAT10_SET_NW_DST },
2791     { OFPUTIL_A_SET_NW_TOS,   OFPAT10_SET_NW_TOS },
2792     { OFPUTIL_A_SET_TP_SRC,   OFPAT10_SET_TP_SRC },
2793     { OFPUTIL_A_SET_TP_DST,   OFPAT10_SET_TP_DST },
2794     { OFPUTIL_A_ENQUEUE,      OFPAT10_ENQUEUE },
2795     { 0, 0 },
2796 };
2797
2798 static const struct ofputil_action_bit_translation of11_action_bits[] = {
2799     { OFPUTIL_A_OUTPUT,         OFPAT11_OUTPUT },
2800     { OFPUTIL_A_SET_VLAN_VID,   OFPAT11_SET_VLAN_VID },
2801     { OFPUTIL_A_SET_VLAN_PCP,   OFPAT11_SET_VLAN_PCP },
2802     { OFPUTIL_A_SET_DL_SRC,     OFPAT11_SET_DL_SRC },
2803     { OFPUTIL_A_SET_DL_DST,     OFPAT11_SET_DL_DST },
2804     { OFPUTIL_A_SET_NW_SRC,     OFPAT11_SET_NW_SRC },
2805     { OFPUTIL_A_SET_NW_DST,     OFPAT11_SET_NW_DST },
2806     { OFPUTIL_A_SET_NW_TOS,     OFPAT11_SET_NW_TOS },
2807     { OFPUTIL_A_SET_NW_ECN,     OFPAT11_SET_NW_ECN },
2808     { OFPUTIL_A_SET_TP_SRC,     OFPAT11_SET_TP_SRC },
2809     { OFPUTIL_A_SET_TP_DST,     OFPAT11_SET_TP_DST },
2810     { OFPUTIL_A_COPY_TTL_OUT,   OFPAT11_COPY_TTL_OUT },
2811     { OFPUTIL_A_COPY_TTL_IN,    OFPAT11_COPY_TTL_IN },
2812     { OFPUTIL_A_SET_MPLS_LABEL, OFPAT11_SET_MPLS_LABEL },
2813     { OFPUTIL_A_SET_MPLS_TC,    OFPAT11_SET_MPLS_TC },
2814     { OFPUTIL_A_SET_MPLS_TTL,   OFPAT11_SET_MPLS_TTL },
2815     { OFPUTIL_A_DEC_MPLS_TTL,   OFPAT11_DEC_MPLS_TTL },
2816     { OFPUTIL_A_PUSH_VLAN,      OFPAT11_PUSH_VLAN },
2817     { OFPUTIL_A_POP_VLAN,       OFPAT11_POP_VLAN },
2818     { OFPUTIL_A_PUSH_MPLS,      OFPAT11_PUSH_MPLS },
2819     { OFPUTIL_A_POP_MPLS,       OFPAT11_POP_MPLS },
2820     { OFPUTIL_A_SET_QUEUE,      OFPAT11_SET_QUEUE },
2821     { OFPUTIL_A_GROUP,          OFPAT11_GROUP },
2822     { OFPUTIL_A_SET_NW_TTL,     OFPAT11_SET_NW_TTL },
2823     { OFPUTIL_A_DEC_NW_TTL,     OFPAT11_DEC_NW_TTL },
2824     { 0, 0 },
2825 };
2826
2827 static enum ofputil_action_bitmap
2828 decode_action_bits(ovs_be32 of_actions,
2829                    const struct ofputil_action_bit_translation *x)
2830 {
2831     enum ofputil_action_bitmap ofputil_actions;
2832
2833     ofputil_actions = 0;
2834     for (; x->ofputil_bit; x++) {
2835         if (of_actions & htonl(1u << x->of_bit)) {
2836             ofputil_actions |= x->ofputil_bit;
2837         }
2838     }
2839     return ofputil_actions;
2840 }
2841
2842 /* Decodes an OpenFlow 1.0 or 1.1 "switch_features" structure 'osf' into an
2843  * abstract representation in '*features'.  Initializes '*b' to iterate over
2844  * the OpenFlow port structures following 'osf' with later calls to
2845  * ofputil_pull_phy_port().  Returns 0 if successful, otherwise an
2846  * OFPERR_* value.  */
2847 enum ofperr
2848 ofputil_decode_switch_features(const struct ofp_switch_features *osf,
2849                                struct ofputil_switch_features *features,
2850                                struct ofpbuf *b)
2851 {
2852     ofpbuf_use_const(b, osf, ntohs(osf->header.length));
2853     ofpbuf_pull(b, sizeof *osf);
2854
2855     features->datapath_id = ntohll(osf->datapath_id);
2856     features->n_buffers = ntohl(osf->n_buffers);
2857     features->n_tables = osf->n_tables;
2858
2859     features->capabilities = ntohl(osf->capabilities) & OFPC_COMMON;
2860
2861     if (b->size % ofputil_get_phy_port_size(osf->header.version)) {
2862         return OFPERR_OFPBRC_BAD_LEN;
2863     }
2864
2865     if (osf->header.version == OFP10_VERSION) {
2866         if (osf->capabilities & htonl(OFPC10_STP)) {
2867             features->capabilities |= OFPUTIL_C_STP;
2868         }
2869         features->actions = decode_action_bits(osf->actions, of10_action_bits);
2870     } else if (osf->header.version == OFP11_VERSION) {
2871         if (osf->capabilities & htonl(OFPC11_GROUP_STATS)) {
2872             features->capabilities |= OFPUTIL_C_GROUP_STATS;
2873         }
2874         features->actions = decode_action_bits(osf->actions, of11_action_bits);
2875     } else {
2876         return OFPERR_OFPBRC_BAD_VERSION;
2877     }
2878
2879     return 0;
2880 }
2881
2882 /* Returns true if the maximum number of ports are in 'osf'. */
2883 static bool
2884 max_ports_in_features(const struct ofp_switch_features *osf)
2885 {
2886     size_t pp_size = ofputil_get_phy_port_size(osf->header.version);
2887     return ntohs(osf->header.length) + pp_size > UINT16_MAX;
2888 }
2889
2890 /* Given a buffer 'b' that contains a Features Reply message, checks if
2891  * it contains the maximum number of ports that will fit.  If so, it
2892  * returns true and removes the ports from the message.  The caller
2893  * should then send an OFPST_PORT_DESC stats request to get the ports,
2894  * since the switch may have more ports than could be represented in the
2895  * Features Reply.  Otherwise, returns false.
2896  */
2897 bool
2898 ofputil_switch_features_ports_trunc(struct ofpbuf *b)
2899 {
2900     struct ofp_switch_features *osf = b->data;
2901
2902     if (max_ports_in_features(osf)) {
2903         /* Remove all the ports. */
2904         b->size = sizeof(*osf);
2905         update_openflow_length(b);
2906
2907         return true;
2908     }
2909
2910     return false;
2911 }
2912
2913 static ovs_be32
2914 encode_action_bits(enum ofputil_action_bitmap ofputil_actions,
2915                    const struct ofputil_action_bit_translation *x)
2916 {
2917     uint32_t of_actions;
2918
2919     of_actions = 0;
2920     for (; x->ofputil_bit; x++) {
2921         if (ofputil_actions & x->ofputil_bit) {
2922             of_actions |= 1 << x->of_bit;
2923         }
2924     }
2925     return htonl(of_actions);
2926 }
2927
2928 /* Returns a buffer owned by the caller that encodes 'features' in the format
2929  * required by 'protocol' with the given 'xid'.  The caller should append port
2930  * information to the buffer with subsequent calls to
2931  * ofputil_put_switch_features_port(). */
2932 struct ofpbuf *
2933 ofputil_encode_switch_features(const struct ofputil_switch_features *features,
2934                                enum ofputil_protocol protocol, ovs_be32 xid)
2935 {
2936     struct ofp_switch_features *osf;
2937     struct ofpbuf *b;
2938
2939     osf = make_openflow_xid(sizeof *osf, OFPT_FEATURES_REPLY, xid, &b);
2940     osf->header.version = ofputil_protocol_to_ofp_version(protocol);
2941     osf->datapath_id = htonll(features->datapath_id);
2942     osf->n_buffers = htonl(features->n_buffers);
2943     osf->n_tables = features->n_tables;
2944
2945     osf->capabilities = htonl(features->capabilities & OFPC_COMMON);
2946     if (osf->header.version == OFP10_VERSION) {
2947         if (features->capabilities & OFPUTIL_C_STP) {
2948             osf->capabilities |= htonl(OFPC10_STP);
2949         }
2950         osf->actions = encode_action_bits(features->actions, of10_action_bits);
2951     } else {
2952         if (features->capabilities & OFPUTIL_C_GROUP_STATS) {
2953             osf->capabilities |= htonl(OFPC11_GROUP_STATS);
2954         }
2955         osf->actions = encode_action_bits(features->actions, of11_action_bits);
2956     }
2957
2958     return b;
2959 }
2960
2961 /* Encodes 'pp' into the format required by the switch_features message already
2962  * in 'b', which should have been returned by ofputil_encode_switch_features(),
2963  * and appends the encoded version to 'b'. */
2964 void
2965 ofputil_put_switch_features_port(const struct ofputil_phy_port *pp,
2966                                  struct ofpbuf *b)
2967 {
2968     const struct ofp_switch_features *osf = b->data;
2969
2970     ofputil_put_phy_port(osf->header.version, pp, b);
2971 }
2972 \f
2973 /* ofputil_port_status */
2974
2975 /* Decodes the OpenFlow "port status" message in '*ops' into an abstract form
2976  * in '*ps'.  Returns 0 if successful, otherwise an OFPERR_* value. */
2977 enum ofperr
2978 ofputil_decode_port_status(const struct ofp_port_status *ops,
2979                            struct ofputil_port_status *ps)
2980 {
2981     struct ofpbuf b;
2982     int retval;
2983
2984     if (ops->reason != OFPPR_ADD &&
2985         ops->reason != OFPPR_DELETE &&
2986         ops->reason != OFPPR_MODIFY) {
2987         return OFPERR_NXBRC_BAD_REASON;
2988     }
2989     ps->reason = ops->reason;
2990
2991     ofpbuf_use_const(&b, ops, ntohs(ops->header.length));
2992     ofpbuf_pull(&b, sizeof *ops);
2993     retval = ofputil_pull_phy_port(ops->header.version, &b, &ps->desc);
2994     assert(retval != EOF);
2995     return retval;
2996 }
2997
2998 /* Converts the abstract form of a "port status" message in '*ps' into an
2999  * OpenFlow message suitable for 'protocol', and returns that encoded form in
3000  * a buffer owned by the caller. */
3001 struct ofpbuf *
3002 ofputil_encode_port_status(const struct ofputil_port_status *ps,
3003                            enum ofputil_protocol protocol)
3004 {
3005     struct ofp_port_status *ops;
3006     struct ofpbuf *b;
3007
3008     b = ofpbuf_new(sizeof *ops + sizeof(struct ofp11_port));
3009     ops = put_openflow_xid(sizeof *ops, OFPT_PORT_STATUS, htonl(0), b);
3010     ops->header.version = ofputil_protocol_to_ofp_version(protocol);
3011     ops->reason = ps->reason;
3012     ofputil_put_phy_port(ops->header.version, &ps->desc, b);
3013     update_openflow_length(b);
3014     return b;
3015 }
3016 \f
3017 /* ofputil_port_mod */
3018
3019 /* Decodes the OpenFlow "port mod" message in '*oh' into an abstract form in
3020  * '*pm'.  Returns 0 if successful, otherwise an OFPERR_* value. */
3021 enum ofperr
3022 ofputil_decode_port_mod(const struct ofp_header *oh,
3023                         struct ofputil_port_mod *pm)
3024 {
3025     if (oh->version == OFP10_VERSION) {
3026         const struct ofp10_port_mod *opm = (const struct ofp10_port_mod *) oh;
3027
3028         if (oh->length != htons(sizeof *opm)) {
3029             return OFPERR_OFPBRC_BAD_LEN;
3030         }
3031
3032         pm->port_no = ntohs(opm->port_no);
3033         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
3034         pm->config = ntohl(opm->config) & OFPPC10_ALL;
3035         pm->mask = ntohl(opm->mask) & OFPPC10_ALL;
3036         pm->advertise = netdev_port_features_from_ofp10(opm->advertise);
3037     } else if (oh->version == OFP11_VERSION) {
3038         const struct ofp11_port_mod *opm = (const struct ofp11_port_mod *) oh;
3039         enum ofperr error;
3040
3041         if (oh->length != htons(sizeof *opm)) {
3042             return OFPERR_OFPBRC_BAD_LEN;
3043         }
3044
3045         error = ofputil_port_from_ofp11(opm->port_no, &pm->port_no);
3046         if (error) {
3047             return error;
3048         }
3049
3050         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
3051         pm->config = ntohl(opm->config) & OFPPC11_ALL;
3052         pm->mask = ntohl(opm->mask) & OFPPC11_ALL;
3053         pm->advertise = netdev_port_features_from_ofp11(opm->advertise);
3054     } else {
3055         return OFPERR_OFPBRC_BAD_VERSION;
3056     }
3057
3058     pm->config &= pm->mask;
3059     return 0;
3060 }
3061
3062 /* Converts the abstract form of a "port mod" message in '*pm' into an OpenFlow
3063  * message suitable for 'protocol', and returns that encoded form in a buffer
3064  * owned by the caller. */
3065 struct ofpbuf *
3066 ofputil_encode_port_mod(const struct ofputil_port_mod *pm,
3067                         enum ofputil_protocol protocol)
3068 {
3069     uint8_t ofp_version = ofputil_protocol_to_ofp_version(protocol);
3070     struct ofpbuf *b;
3071
3072     if (ofp_version == OFP10_VERSION) {
3073         struct ofp10_port_mod *opm;
3074
3075         opm = make_openflow(sizeof *opm, OFPT10_PORT_MOD, &b);
3076         opm->port_no = htons(pm->port_no);
3077         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
3078         opm->config = htonl(pm->config & OFPPC10_ALL);
3079         opm->mask = htonl(pm->mask & OFPPC10_ALL);
3080         opm->advertise = netdev_port_features_to_ofp10(pm->advertise);
3081     } else if (ofp_version == OFP11_VERSION) {
3082         struct ofp11_port_mod *opm;
3083
3084         opm = make_openflow(sizeof *opm, OFPT11_PORT_MOD, &b);
3085         opm->port_no = htonl(pm->port_no);
3086         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
3087         opm->config = htonl(pm->config & OFPPC11_ALL);
3088         opm->mask = htonl(pm->mask & OFPPC11_ALL);
3089         opm->advertise = netdev_port_features_to_ofp11(pm->advertise);
3090     } else {
3091         NOT_REACHED();
3092     }
3093
3094     return b;
3095 }
3096
3097 struct ofpbuf *
3098 ofputil_encode_packet_out(const struct ofputil_packet_out *po)
3099 {
3100     struct ofp_packet_out *opo;
3101     struct ofpbuf *msg;
3102     size_t size;
3103
3104     size = sizeof *opo + po->ofpacts_len;
3105     if (po->buffer_id == UINT32_MAX) {
3106         size += po->packet_len;
3107     }
3108
3109     msg = ofpbuf_new(size);
3110     put_openflow(sizeof *opo, OFPT_PACKET_OUT, msg);
3111     ofpacts_put_openflow10(po->ofpacts, po->ofpacts_len, msg);
3112
3113     opo = msg->data;
3114     opo->buffer_id = htonl(po->buffer_id);
3115     opo->in_port = htons(po->in_port);
3116     opo->actions_len = htons(msg->size - sizeof *opo);
3117
3118     if (po->buffer_id == UINT32_MAX) {
3119         ofpbuf_put(msg, po->packet, po->packet_len);
3120     }
3121
3122     update_openflow_length(msg);
3123
3124     return msg;
3125 }
3126
3127 /* Returns a string representing the message type of 'type'.  The string is the
3128  * enumeration constant for the type, e.g. "OFPT_HELLO".  For statistics
3129  * messages, the constant is followed by "request" or "reply",
3130  * e.g. "OFPST_AGGREGATE reply". */
3131 const char *
3132 ofputil_msg_type_name(const struct ofputil_msg_type *type)
3133 {
3134     return type->name;
3135 }
3136 \f
3137 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
3138  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
3139  * an arbitrary transaction id.  Allocated bytes beyond the header, if any, are
3140  * zeroed.
3141  *
3142  * The caller is responsible for freeing '*bufferp' when it is no longer
3143  * needed.
3144  *
3145  * The OpenFlow header length is initially set to 'openflow_len'; if the
3146  * message is later extended, the length should be updated with
3147  * update_openflow_length() before sending.
3148  *
3149  * Returns the header. */
3150 void *
3151 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp)
3152 {
3153     *bufferp = ofpbuf_new(openflow_len);
3154     return put_openflow_xid(openflow_len, type, alloc_xid(), *bufferp);
3155 }
3156
3157 /* Similar to make_openflow() but creates a Nicira vendor extension message
3158  * with the specific 'subtype'.  'subtype' should be in host byte order. */
3159 void *
3160 make_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf **bufferp)
3161 {
3162     return make_nxmsg_xid(openflow_len, subtype, alloc_xid(), bufferp);
3163 }
3164
3165 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
3166  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
3167  * transaction id 'xid'.  Allocated bytes beyond the header, if any, are
3168  * zeroed.
3169  *
3170  * The caller is responsible for freeing '*bufferp' when it is no longer
3171  * needed.
3172  *
3173  * The OpenFlow header length is initially set to 'openflow_len'; if the
3174  * message is later extended, the length should be updated with
3175  * update_openflow_length() before sending.
3176  *
3177  * Returns the header. */
3178 void *
3179 make_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
3180                   struct ofpbuf **bufferp)
3181 {
3182     *bufferp = ofpbuf_new(openflow_len);
3183     return put_openflow_xid(openflow_len, type, xid, *bufferp);
3184 }
3185
3186 /* Similar to make_openflow_xid() but creates a Nicira vendor extension message
3187  * with the specific 'subtype'.  'subtype' should be in host byte order. */
3188 void *
3189 make_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
3190                struct ofpbuf **bufferp)
3191 {
3192     *bufferp = ofpbuf_new(openflow_len);
3193     return put_nxmsg_xid(openflow_len, subtype, xid, *bufferp);
3194 }
3195
3196 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
3197  * with the given 'type' and an arbitrary transaction id.  Allocated bytes
3198  * beyond the header, if any, are zeroed.
3199  *
3200  * The OpenFlow header length is initially set to 'openflow_len'; if the
3201  * message is later extended, the length should be updated with
3202  * update_openflow_length() before sending.
3203  *
3204  * Returns the header. */
3205 void *
3206 put_openflow(size_t openflow_len, uint8_t type, struct ofpbuf *buffer)
3207 {
3208     return put_openflow_xid(openflow_len, type, alloc_xid(), buffer);
3209 }
3210
3211 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
3212  * with the given 'type' and an transaction id 'xid'.  Allocated bytes beyond
3213  * the header, if any, are zeroed.
3214  *
3215  * The OpenFlow header length is initially set to 'openflow_len'; if the
3216  * message is later extended, the length should be updated with
3217  * update_openflow_length() before sending.
3218  *
3219  * Returns the header. */
3220 void *
3221 put_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
3222                  struct ofpbuf *buffer)
3223 {
3224     struct ofp_header *oh;
3225
3226     assert(openflow_len >= sizeof *oh);
3227     assert(openflow_len <= UINT16_MAX);
3228
3229     oh = ofpbuf_put_uninit(buffer, openflow_len);
3230     oh->version = OFP10_VERSION;
3231     oh->type = type;
3232     oh->length = htons(openflow_len);
3233     oh->xid = xid;
3234     memset(oh + 1, 0, openflow_len - sizeof *oh);
3235     return oh;
3236 }
3237
3238 /* Similar to put_openflow() but append a Nicira vendor extension message with
3239  * the specific 'subtype'.  'subtype' should be in host byte order. */
3240 void *
3241 put_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf *buffer)
3242 {
3243     return put_nxmsg_xid(openflow_len, subtype, alloc_xid(), buffer);
3244 }
3245
3246 /* Similar to put_openflow_xid() but append a Nicira vendor extension message
3247  * with the specific 'subtype'.  'subtype' should be in host byte order. */
3248 void *
3249 put_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
3250               struct ofpbuf *buffer)
3251 {
3252     struct nicira_header *nxh;
3253
3254     nxh = put_openflow_xid(openflow_len, OFPT_VENDOR, xid, buffer);
3255     nxh->vendor = htonl(NX_VENDOR_ID);
3256     nxh->subtype = htonl(subtype);
3257     return nxh;
3258 }
3259
3260 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
3261  * 'buffer->size'. */
3262 void
3263 update_openflow_length(struct ofpbuf *buffer)
3264 {
3265     struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
3266     oh->length = htons(buffer->size);
3267 }
3268
3269 static void
3270 put_stats__(ovs_be32 xid, uint8_t ofp_type,
3271             ovs_be16 ofpst_type, ovs_be32 nxst_subtype,
3272             struct ofpbuf *msg)
3273 {
3274     if (ofpst_type == htons(OFPST_VENDOR)) {
3275         struct nicira_stats_msg *nsm;
3276
3277         nsm = put_openflow_xid(sizeof *nsm, ofp_type, xid, msg);
3278         nsm->vsm.osm.type = ofpst_type;
3279         nsm->vsm.vendor = htonl(NX_VENDOR_ID);
3280         nsm->subtype = nxst_subtype;
3281     } else {
3282         struct ofp_stats_msg *osm;
3283
3284         osm = put_openflow_xid(sizeof *osm, ofp_type, xid, msg);
3285         osm->type = ofpst_type;
3286     }
3287 }
3288
3289 /* Creates a statistics request message with total length 'openflow_len'
3290  * (including all headers) and the given 'ofpst_type', and stores the buffer
3291  * containing the new message in '*bufferp'.  If 'ofpst_type' is OFPST_VENDOR
3292  * then 'nxst_subtype' is used as the Nicira vendor extension statistics
3293  * subtype (otherwise 'nxst_subtype' is ignored).
3294  *
3295  * Initializes bytes following the headers to all-bits-zero.
3296  *
3297  * Returns the first byte of the new message. */
3298 void *
3299 ofputil_make_stats_request(size_t openflow_len, uint16_t ofpst_type,
3300                            uint32_t nxst_subtype, struct ofpbuf **bufferp)
3301 {
3302     struct ofpbuf *msg;
3303
3304     msg = *bufferp = ofpbuf_new(openflow_len);
3305     put_stats__(alloc_xid(), OFPT10_STATS_REQUEST,
3306                 htons(ofpst_type), htonl(nxst_subtype), msg);
3307     ofpbuf_padto(msg, openflow_len);
3308
3309     return msg->data;
3310 }
3311
3312 static void
3313 put_stats_reply__(const struct ofp_stats_msg *request, struct ofpbuf *msg)
3314 {
3315     assert(request->header.type == OFPT10_STATS_REQUEST ||
3316            request->header.type == OFPT10_STATS_REPLY);
3317     put_stats__(request->header.xid, OFPT10_STATS_REPLY, request->type,
3318                 (request->type != htons(OFPST_VENDOR)
3319                  ? htonl(0)
3320                  : ((const struct nicira_stats_msg *) request)->subtype),
3321                 msg);
3322 }
3323
3324 /* Creates a statistics reply message with total length 'openflow_len'
3325  * (including all headers) and the same type (either a standard OpenFlow
3326  * statistics type or a Nicira extension type and subtype) as 'request', and
3327  * stores the buffer containing the new message in '*bufferp'.
3328  *
3329  * Initializes bytes following the headers to all-bits-zero.
3330  *
3331  * Returns the first byte of the new message. */
3332 void *
3333 ofputil_make_stats_reply(size_t openflow_len,
3334                          const struct ofp_stats_msg *request,
3335                          struct ofpbuf **bufferp)
3336 {
3337     struct ofpbuf *msg;
3338
3339     msg = *bufferp = ofpbuf_new(openflow_len);
3340     put_stats_reply__(request, msg);
3341     ofpbuf_padto(msg, openflow_len);
3342
3343     return msg->data;
3344 }
3345
3346 /* Initializes 'replies' as a list of ofpbufs that will contain a series of
3347  * replies to 'request', which should be an OpenFlow or Nicira extension
3348  * statistics request.  Initially 'replies' will have a single reply message
3349  * that has only a header.  The functions ofputil_reserve_stats_reply() and
3350  * ofputil_append_stats_reply() may be used to add to the reply. */
3351 void
3352 ofputil_start_stats_reply(const struct ofp_stats_msg *request,
3353                           struct list *replies)
3354 {
3355     struct ofpbuf *msg;
3356
3357     msg = ofpbuf_new(1024);
3358     put_stats_reply__(request, msg);
3359
3360     list_init(replies);
3361     list_push_back(replies, &msg->list_node);
3362 }
3363
3364 /* Prepares to append up to 'len' bytes to the series of statistics replies in
3365  * 'replies', which should have been initialized with
3366  * ofputil_start_stats_reply().  Returns an ofpbuf with at least 'len' bytes of
3367  * tailroom.  (The 'len' bytes have not actually be allocated; the caller must
3368  * do so with e.g. ofpbuf_put_uninit().) */
3369 struct ofpbuf *
3370 ofputil_reserve_stats_reply(size_t len, struct list *replies)
3371 {
3372     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
3373     struct ofp_stats_msg *osm = msg->data;
3374
3375     if (msg->size + len <= UINT16_MAX) {
3376         ofpbuf_prealloc_tailroom(msg, len);
3377     } else {
3378         osm->flags |= htons(OFPSF_REPLY_MORE);
3379
3380         msg = ofpbuf_new(MAX(1024, sizeof(struct nicira_stats_msg) + len));
3381         put_stats_reply__(osm, msg);
3382         list_push_back(replies, &msg->list_node);
3383     }
3384     return msg;
3385 }
3386
3387 /* Appends 'len' bytes to the series of statistics replies in 'replies', and
3388  * returns the first byte. */
3389 void *
3390 ofputil_append_stats_reply(size_t len, struct list *replies)
3391 {
3392     return ofpbuf_put_uninit(ofputil_reserve_stats_reply(len, replies), len);
3393 }
3394
3395 /* Sometimes, when composing stats replies, it's difficult to predict how long
3396  * an individual reply chunk will be before actually encoding it into the reply
3397  * buffer.  This function allows easy handling of this case: just encode the
3398  * reply, then use this function to break the message into two pieces if it
3399  * exceeds the OpenFlow message limit.
3400  *
3401  * In detail, if the final stats message in 'replies' is too long for OpenFlow,
3402  * this function breaks it into two separate stats replies, the first one with
3403  * the first 'start_ofs' bytes, the second one containing the bytes from that
3404  * offset onward. */
3405 void
3406 ofputil_postappend_stats_reply(size_t start_ofs, struct list *replies)
3407 {
3408     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
3409
3410     assert(start_ofs <= UINT16_MAX);
3411     if (msg->size > UINT16_MAX) {
3412         size_t len = msg->size - start_ofs;
3413         memcpy(ofputil_append_stats_reply(len, replies),
3414                (const uint8_t *) msg->data + start_ofs, len);
3415         msg->size = start_ofs;
3416     }
3417 }
3418
3419 /* Returns the first byte past the ofp_stats_msg header in 'oh'. */
3420 const void *
3421 ofputil_stats_body(const struct ofp_header *oh)
3422 {
3423     assert(oh->type == OFPT10_STATS_REQUEST || oh->type == OFPT10_STATS_REPLY);
3424     return (const struct ofp_stats_msg *) oh + 1;
3425 }
3426
3427 /* Returns the number of bytes past the ofp_stats_msg header in 'oh'. */
3428 size_t
3429 ofputil_stats_body_len(const struct ofp_header *oh)
3430 {
3431     assert(oh->type == OFPT10_STATS_REQUEST || oh->type == OFPT10_STATS_REPLY);
3432     return ntohs(oh->length) - sizeof(struct ofp_stats_msg);
3433 }
3434
3435 /* Returns the first byte past the nicira_stats_msg header in 'oh'. */
3436 const void *
3437 ofputil_nxstats_body(const struct ofp_header *oh)
3438 {
3439     assert(oh->type == OFPT10_STATS_REQUEST || oh->type == OFPT10_STATS_REPLY);
3440     return ((const struct nicira_stats_msg *) oh) + 1;
3441 }
3442
3443 /* Returns the number of bytes past the nicira_stats_msg header in 'oh'. */
3444 size_t
3445 ofputil_nxstats_body_len(const struct ofp_header *oh)
3446 {
3447     assert(oh->type == OFPT10_STATS_REQUEST || oh->type == OFPT10_STATS_REPLY);
3448     return ntohs(oh->length) - sizeof(struct nicira_stats_msg);
3449 }
3450
3451 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
3452 struct ofpbuf *
3453 make_echo_request(void)
3454 {
3455     struct ofp_header *rq;
3456     struct ofpbuf *out = ofpbuf_new(sizeof *rq);
3457     rq = ofpbuf_put_uninit(out, sizeof *rq);
3458     rq->version = OFP10_VERSION;
3459     rq->type = OFPT_ECHO_REQUEST;
3460     rq->length = htons(sizeof *rq);
3461     rq->xid = htonl(0);
3462     return out;
3463 }
3464
3465 /* Creates and returns an OFPT_ECHO_REPLY message matching the
3466  * OFPT_ECHO_REQUEST message in 'rq'. */
3467 struct ofpbuf *
3468 make_echo_reply(const struct ofp_header *rq)
3469 {
3470     size_t size = ntohs(rq->length);
3471     struct ofpbuf *out = ofpbuf_new(size);
3472     struct ofp_header *reply = ofpbuf_put(out, rq, size);
3473     reply->type = OFPT_ECHO_REPLY;
3474     return out;
3475 }
3476
3477 struct ofpbuf *
3478 ofputil_encode_barrier_request(void)
3479 {
3480     struct ofpbuf *msg;
3481
3482     make_openflow(sizeof(struct ofp_header), OFPT10_BARRIER_REQUEST, &msg);
3483     return msg;
3484 }
3485
3486 const char *
3487 ofputil_frag_handling_to_string(enum ofp_config_flags flags)
3488 {
3489     switch (flags & OFPC_FRAG_MASK) {
3490     case OFPC_FRAG_NORMAL:   return "normal";
3491     case OFPC_FRAG_DROP:     return "drop";
3492     case OFPC_FRAG_REASM:    return "reassemble";
3493     case OFPC_FRAG_NX_MATCH: return "nx-match";
3494     }
3495
3496     NOT_REACHED();
3497 }
3498
3499 bool
3500 ofputil_frag_handling_from_string(const char *s, enum ofp_config_flags *flags)
3501 {
3502     if (!strcasecmp(s, "normal")) {
3503         *flags = OFPC_FRAG_NORMAL;
3504     } else if (!strcasecmp(s, "drop")) {
3505         *flags = OFPC_FRAG_DROP;
3506     } else if (!strcasecmp(s, "reassemble")) {
3507         *flags = OFPC_FRAG_REASM;
3508     } else if (!strcasecmp(s, "nx-match")) {
3509         *flags = OFPC_FRAG_NX_MATCH;
3510     } else {
3511         return false;
3512     }
3513     return true;
3514 }
3515
3516 /* Converts the OpenFlow 1.1+ port number 'ofp11_port' into an OpenFlow 1.0
3517  * port number and stores the latter in '*ofp10_port', for the purpose of
3518  * decoding OpenFlow 1.1+ protocol messages.  Returns 0 if successful,
3519  * otherwise an OFPERR_* number.
3520  *
3521  * See the definition of OFP11_MAX for an explanation of the mapping. */
3522 enum ofperr
3523 ofputil_port_from_ofp11(ovs_be32 ofp11_port, uint16_t *ofp10_port)
3524 {
3525     uint32_t ofp11_port_h = ntohl(ofp11_port);
3526
3527     if (ofp11_port_h < OFPP_MAX) {
3528         *ofp10_port = ofp11_port_h;
3529         return 0;
3530     } else if (ofp11_port_h >= OFPP11_MAX) {
3531         *ofp10_port = ofp11_port_h - OFPP11_OFFSET;
3532         return 0;
3533     } else {
3534         VLOG_WARN_RL(&bad_ofmsg_rl, "port %"PRIu32" is outside the supported "
3535                      "range 0 through %d or 0x%"PRIx32" through 0x%"PRIx32,
3536                      ofp11_port_h, OFPP_MAX - 1,
3537                      (uint32_t) OFPP11_MAX, UINT32_MAX);
3538         return OFPERR_OFPBAC_BAD_OUT_PORT;
3539     }
3540 }
3541
3542 /* Returns the OpenFlow 1.1+ port number equivalent to the OpenFlow 1.0 port
3543  * number 'ofp10_port', for encoding OpenFlow 1.1+ protocol messages.
3544  *
3545  * See the definition of OFP11_MAX for an explanation of the mapping. */
3546 ovs_be32
3547 ofputil_port_to_ofp11(uint16_t ofp10_port)
3548 {
3549     return htonl(ofp10_port < OFPP_MAX
3550                  ? ofp10_port
3551                  : ofp10_port + OFPP11_OFFSET);
3552 }
3553
3554 /* Checks that 'port' is a valid output port for the OFPAT10_OUTPUT action, given
3555  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
3556  * 'port' is valid, otherwise an OpenFlow return code. */
3557 enum ofperr
3558 ofputil_check_output_port(uint16_t port, int max_ports)
3559 {
3560     switch (port) {
3561     case OFPP_IN_PORT:
3562     case OFPP_TABLE:
3563     case OFPP_NORMAL:
3564     case OFPP_FLOOD:
3565     case OFPP_ALL:
3566     case OFPP_CONTROLLER:
3567     case OFPP_NONE:
3568     case OFPP_LOCAL:
3569         return 0;
3570
3571     default:
3572         if (port < max_ports) {
3573             return 0;
3574         }
3575         return OFPERR_OFPBAC_BAD_OUT_PORT;
3576     }
3577 }
3578
3579 #define OFPUTIL_NAMED_PORTS                     \
3580         OFPUTIL_NAMED_PORT(IN_PORT)             \
3581         OFPUTIL_NAMED_PORT(TABLE)               \
3582         OFPUTIL_NAMED_PORT(NORMAL)              \
3583         OFPUTIL_NAMED_PORT(FLOOD)               \
3584         OFPUTIL_NAMED_PORT(ALL)                 \
3585         OFPUTIL_NAMED_PORT(CONTROLLER)          \
3586         OFPUTIL_NAMED_PORT(LOCAL)               \
3587         OFPUTIL_NAMED_PORT(NONE)
3588
3589 /* Checks whether 's' is the string representation of an OpenFlow port number,
3590  * either as an integer or a string name (e.g. "LOCAL").  If it is, stores the
3591  * number in '*port' and returns true.  Otherwise, returns false. */
3592 bool
3593 ofputil_port_from_string(const char *name, uint16_t *port)
3594 {
3595     struct pair {
3596         const char *name;
3597         uint16_t value;
3598     };
3599     static const struct pair pairs[] = {
3600 #define OFPUTIL_NAMED_PORT(NAME) {#NAME, OFPP_##NAME},
3601         OFPUTIL_NAMED_PORTS
3602 #undef OFPUTIL_NAMED_PORT
3603     };
3604     static const int n_pairs = ARRAY_SIZE(pairs);
3605     int i;
3606
3607     if (str_to_int(name, 0, &i) && i >= 0 && i < UINT16_MAX) {
3608         *port = i;
3609         return true;
3610     }
3611
3612     for (i = 0; i < n_pairs; i++) {
3613         if (!strcasecmp(name, pairs[i].name)) {
3614             *port = pairs[i].value;
3615             return true;
3616         }
3617     }
3618     return false;
3619 }
3620
3621 /* Appends to 's' a string representation of the OpenFlow port number 'port'.
3622  * Most ports' string representation is just the port number, but for special
3623  * ports, e.g. OFPP_LOCAL, it is the name, e.g. "LOCAL". */
3624 void
3625 ofputil_format_port(uint16_t port, struct ds *s)
3626 {
3627     const char *name;
3628
3629     switch (port) {
3630 #define OFPUTIL_NAMED_PORT(NAME) case OFPP_##NAME: name = #NAME; break;
3631         OFPUTIL_NAMED_PORTS
3632 #undef OFPUTIL_NAMED_PORT
3633
3634     default:
3635         ds_put_format(s, "%"PRIu16, port);
3636         return;
3637     }
3638     ds_put_cstr(s, name);
3639 }
3640
3641 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
3642  * 'ofp_version', tries to pull the first element from the array.  If
3643  * successful, initializes '*pp' with an abstract representation of the
3644  * port and returns 0.  If no ports remain to be decoded, returns EOF.
3645  * On an error, returns a positive OFPERR_* value. */
3646 int
3647 ofputil_pull_phy_port(uint8_t ofp_version, struct ofpbuf *b,
3648                       struct ofputil_phy_port *pp)
3649 {
3650     if (ofp_version == OFP10_VERSION) {
3651         const struct ofp10_phy_port *opp = ofpbuf_try_pull(b, sizeof *opp);
3652         return opp ? ofputil_decode_ofp10_phy_port(pp, opp) : EOF;
3653     } else {
3654         const struct ofp11_port *op = ofpbuf_try_pull(b, sizeof *op);
3655         return op ? ofputil_decode_ofp11_port(pp, op) : EOF;
3656     }
3657 }
3658
3659 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
3660  * 'ofp_version', returns the number of elements. */
3661 size_t ofputil_count_phy_ports(uint8_t ofp_version, struct ofpbuf *b)
3662 {
3663     return b->size / ofputil_get_phy_port_size(ofp_version);
3664 }
3665
3666 /* Returns the 'enum ofputil_action_code' corresponding to 'name' (e.g. if
3667  * 'name' is "output" then the return value is OFPUTIL_OFPAT10_OUTPUT), or -1 if
3668  * 'name' is not the name of any action.
3669  *
3670  * ofp-util.def lists the mapping from names to action. */
3671 int
3672 ofputil_action_code_from_name(const char *name)
3673 {
3674     static const char *names[OFPUTIL_N_ACTIONS] = {
3675         NULL,
3676 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)           NAME,
3677 #define OFPAT11_ACTION(ENUM, STRUCT, NAME)           NAME,
3678 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) NAME,
3679 #include "ofp-util.def"
3680     };
3681
3682     const char **p;
3683
3684     for (p = names; p < &names[ARRAY_SIZE(names)]; p++) {
3685         if (*p && !strcasecmp(name, *p)) {
3686             return p - names;
3687         }
3688     }
3689     return -1;
3690 }
3691
3692 /* Appends an action of the type specified by 'code' to 'buf' and returns the
3693  * action.  Initializes the parts of 'action' that identify it as having type
3694  * <ENUM> and length 'sizeof *action' and zeros the rest.  For actions that
3695  * have variable length, the length used and cleared is that of struct
3696  * <STRUCT>.  */
3697 void *
3698 ofputil_put_action(enum ofputil_action_code code, struct ofpbuf *buf)
3699 {
3700     switch (code) {
3701     case OFPUTIL_ACTION_INVALID:
3702         NOT_REACHED();
3703
3704 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                    \
3705     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
3706 #define OFPAT11_ACTION OFPAT10_ACTION
3707 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)        \
3708     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
3709 #include "ofp-util.def"
3710     }
3711     NOT_REACHED();
3712 }
3713
3714 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                        \
3715     void                                                        \
3716     ofputil_init_##ENUM(struct STRUCT *s)                       \
3717     {                                                           \
3718         memset(s, 0, sizeof *s);                                \
3719         s->type = htons(ENUM);                                  \
3720         s->len = htons(sizeof *s);                              \
3721     }                                                           \
3722                                                                 \
3723     struct STRUCT *                                             \
3724     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
3725     {                                                           \
3726         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
3727         ofputil_init_##ENUM(s);                                 \
3728         return s;                                               \
3729     }
3730 #define OFPAT11_ACTION OFPAT10_ACTION
3731 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)            \
3732     void                                                        \
3733     ofputil_init_##ENUM(struct STRUCT *s)                       \
3734     {                                                           \
3735         memset(s, 0, sizeof *s);                                \
3736         s->type = htons(OFPAT10_VENDOR);                        \
3737         s->len = htons(sizeof *s);                              \
3738         s->vendor = htonl(NX_VENDOR_ID);                        \
3739         s->subtype = htons(ENUM);                               \
3740     }                                                           \
3741                                                                 \
3742     struct STRUCT *                                             \
3743     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
3744     {                                                           \
3745         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
3746         ofputil_init_##ENUM(s);                                 \
3747         return s;                                               \
3748     }
3749 #include "ofp-util.def"
3750
3751 /* "Normalizes" the wildcards in 'rule'.  That means:
3752  *
3753  *    1. If the type of level N is known, then only the valid fields for that
3754  *       level may be specified.  For example, ARP does not have a TOS field,
3755  *       so nw_tos must be wildcarded if 'rule' specifies an ARP flow.
3756  *       Similarly, IPv4 does not have any IPv6 addresses, so ipv6_src and
3757  *       ipv6_dst (and other fields) must be wildcarded if 'rule' specifies an
3758  *       IPv4 flow.
3759  *
3760  *    2. If the type of level N is not known (or not understood by Open
3761  *       vSwitch), then no fields at all for that level may be specified.  For
3762  *       example, Open vSwitch does not understand SCTP, an L4 protocol, so the
3763  *       L4 fields tp_src and tp_dst must be wildcarded if 'rule' specifies an
3764  *       SCTP flow.
3765  */
3766 void
3767 ofputil_normalize_rule(struct cls_rule *rule)
3768 {
3769     enum {
3770         MAY_NW_ADDR     = 1 << 0, /* nw_src, nw_dst */
3771         MAY_TP_ADDR     = 1 << 1, /* tp_src, tp_dst */
3772         MAY_NW_PROTO    = 1 << 2, /* nw_proto */
3773         MAY_IPVx        = 1 << 3, /* tos, frag, ttl */
3774         MAY_ARP_SHA     = 1 << 4, /* arp_sha */
3775         MAY_ARP_THA     = 1 << 5, /* arp_tha */
3776         MAY_IPV6        = 1 << 6, /* ipv6_src, ipv6_dst, ipv6_label */
3777         MAY_ND_TARGET   = 1 << 7  /* nd_target */
3778     } may_match;
3779
3780     struct flow_wildcards wc;
3781
3782     /* Figure out what fields may be matched. */
3783     if (rule->flow.dl_type == htons(ETH_TYPE_IP)) {
3784         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_NW_ADDR;
3785         if (rule->flow.nw_proto == IPPROTO_TCP ||
3786             rule->flow.nw_proto == IPPROTO_UDP ||
3787             rule->flow.nw_proto == IPPROTO_ICMP) {
3788             may_match |= MAY_TP_ADDR;
3789         }
3790     } else if (rule->flow.dl_type == htons(ETH_TYPE_IPV6)) {
3791         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_IPV6;
3792         if (rule->flow.nw_proto == IPPROTO_TCP ||
3793             rule->flow.nw_proto == IPPROTO_UDP) {
3794             may_match |= MAY_TP_ADDR;
3795         } else if (rule->flow.nw_proto == IPPROTO_ICMPV6) {
3796             may_match |= MAY_TP_ADDR;
3797             if (rule->flow.tp_src == htons(ND_NEIGHBOR_SOLICIT)) {
3798                 may_match |= MAY_ND_TARGET | MAY_ARP_SHA;
3799             } else if (rule->flow.tp_src == htons(ND_NEIGHBOR_ADVERT)) {
3800                 may_match |= MAY_ND_TARGET | MAY_ARP_THA;
3801             }
3802         }
3803     } else if (rule->flow.dl_type == htons(ETH_TYPE_ARP)) {
3804         may_match = MAY_NW_PROTO | MAY_NW_ADDR | MAY_ARP_SHA | MAY_ARP_THA;
3805     } else {
3806         may_match = 0;
3807     }
3808
3809     /* Clear the fields that may not be matched. */
3810     wc = rule->wc;
3811     if (!(may_match & MAY_NW_ADDR)) {
3812         wc.nw_src_mask = wc.nw_dst_mask = htonl(0);
3813     }
3814     if (!(may_match & MAY_TP_ADDR)) {
3815         wc.tp_src_mask = wc.tp_dst_mask = htons(0);
3816     }
3817     if (!(may_match & MAY_NW_PROTO)) {
3818         wc.wildcards |= FWW_NW_PROTO;
3819     }
3820     if (!(may_match & MAY_IPVx)) {
3821         wc.wildcards |= FWW_NW_DSCP;
3822         wc.wildcards |= FWW_NW_ECN;
3823         wc.wildcards |= FWW_NW_TTL;
3824     }
3825     if (!(may_match & MAY_ARP_SHA)) {
3826         wc.wildcards |= FWW_ARP_SHA;
3827     }
3828     if (!(may_match & MAY_ARP_THA)) {
3829         wc.wildcards |= FWW_ARP_THA;
3830     }
3831     if (!(may_match & MAY_IPV6)) {
3832         wc.ipv6_src_mask = wc.ipv6_dst_mask = in6addr_any;
3833         wc.wildcards |= FWW_IPV6_LABEL;
3834     }
3835     if (!(may_match & MAY_ND_TARGET)) {
3836         wc.nd_target_mask = in6addr_any;
3837     }
3838
3839     /* Log any changes. */
3840     if (!flow_wildcards_equal(&wc, &rule->wc)) {
3841         bool log = !VLOG_DROP_INFO(&bad_ofmsg_rl);
3842         char *pre = log ? cls_rule_to_string(rule) : NULL;
3843
3844         rule->wc = wc;
3845         cls_rule_zero_wildcarded_fields(rule);
3846
3847         if (log) {
3848             char *post = cls_rule_to_string(rule);
3849             VLOG_INFO("normalization changed ofp_match, details:");
3850             VLOG_INFO(" pre: %s", pre);
3851             VLOG_INFO("post: %s", post);
3852             free(pre);
3853             free(post);
3854         }
3855     }
3856 }
3857
3858 /* Parses a key or a key-value pair from '*stringp'.
3859  *
3860  * On success: Stores the key into '*keyp'.  Stores the value, if present, into
3861  * '*valuep', otherwise an empty string.  Advances '*stringp' past the end of
3862  * the key-value pair, preparing it for another call.  '*keyp' and '*valuep'
3863  * are substrings of '*stringp' created by replacing some of its bytes by null
3864  * terminators.  Returns true.
3865  *
3866  * If '*stringp' is just white space or commas, sets '*keyp' and '*valuep' to
3867  * NULL and returns false. */
3868 bool
3869 ofputil_parse_key_value(char **stringp, char **keyp, char **valuep)
3870 {
3871     char *pos, *key, *value;
3872     size_t key_len;
3873
3874     pos = *stringp;
3875     pos += strspn(pos, ", \t\r\n");
3876     if (*pos == '\0') {
3877         *keyp = *valuep = NULL;
3878         return false;
3879     }
3880
3881     key = pos;
3882     key_len = strcspn(pos, ":=(, \t\r\n");
3883     if (key[key_len] == ':' || key[key_len] == '=') {
3884         /* The value can be separated by a colon. */
3885         size_t value_len;
3886
3887         value = key + key_len + 1;
3888         value_len = strcspn(value, ", \t\r\n");
3889         pos = value + value_len + (value[value_len] != '\0');
3890         value[value_len] = '\0';
3891     } else if (key[key_len] == '(') {
3892         /* The value can be surrounded by balanced parentheses.  The outermost
3893          * set of parentheses is removed. */
3894         int level = 1;
3895         size_t value_len;
3896
3897         value = key + key_len + 1;
3898         for (value_len = 0; level > 0; value_len++) {
3899             switch (value[value_len]) {
3900             case '\0':
3901                 level = 0;
3902                 break;
3903
3904             case '(':
3905                 level++;
3906                 break;
3907
3908             case ')':
3909                 level--;
3910                 break;
3911             }
3912         }
3913         value[value_len - 1] = '\0';
3914         pos = value + value_len;
3915     } else {
3916         /* There might be no value at all. */
3917         value = key + key_len;  /* Will become the empty string below. */
3918         pos = key + key_len + (key[key_len] != '\0');
3919     }
3920     key[key_len] = '\0';
3921
3922     *stringp = pos;
3923     *keyp = key;
3924     *valuep = value;
3925     return true;
3926 }