ofp-util: Reload ofpbuf pointers after nx_put_match().
[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         ofpbuf_put_uninit(reply, sizeof *ofs);
2149         ofpacts_put_openflow10(fs->ofpacts, fs->ofpacts_len, reply);
2150
2151         ofs = ofpbuf_at_assert(reply, start_ofs, sizeof *ofs);
2152         ofs->length = htons(reply->size - start_ofs);
2153         ofs->table_id = fs->table_id;
2154         ofs->pad = 0;
2155         ofputil_cls_rule_to_ofp10_match(&fs->rule, &ofs->match);
2156         ofs->duration_sec = htonl(fs->duration_sec);
2157         ofs->duration_nsec = htonl(fs->duration_nsec);
2158         ofs->priority = htons(fs->rule.priority);
2159         ofs->idle_timeout = htons(fs->idle_timeout);
2160         ofs->hard_timeout = htons(fs->hard_timeout);
2161         memset(ofs->pad2, 0, sizeof ofs->pad2);
2162         put_32aligned_be64(&ofs->cookie, fs->cookie);
2163         put_32aligned_be64(&ofs->packet_count,
2164                            htonll(unknown_to_zero(fs->packet_count)));
2165         put_32aligned_be64(&ofs->byte_count,
2166                            htonll(unknown_to_zero(fs->byte_count)));
2167     } else if (osm->type == htons(OFPST_VENDOR)) {
2168         struct nx_flow_stats *nfs;
2169         int match_len;
2170
2171         ofpbuf_put_uninit(reply, sizeof *nfs);
2172         match_len = nx_put_match(reply, false, &fs->rule, 0, 0);
2173         ofpacts_put_openflow10(fs->ofpacts, fs->ofpacts_len, reply);
2174
2175         nfs = ofpbuf_at_assert(reply, start_ofs, sizeof *nfs);
2176         nfs->length = htons(reply->size - start_ofs);
2177         nfs->table_id = fs->table_id;
2178         nfs->pad = 0;
2179         nfs->duration_sec = htonl(fs->duration_sec);
2180         nfs->duration_nsec = htonl(fs->duration_nsec);
2181         nfs->priority = htons(fs->rule.priority);
2182         nfs->idle_timeout = htons(fs->idle_timeout);
2183         nfs->hard_timeout = htons(fs->hard_timeout);
2184         nfs->idle_age = htons(fs->idle_age < 0 ? 0
2185                               : fs->idle_age < UINT16_MAX ? fs->idle_age + 1
2186                               : UINT16_MAX);
2187         nfs->hard_age = htons(fs->hard_age < 0 ? 0
2188                               : fs->hard_age < UINT16_MAX ? fs->hard_age + 1
2189                               : UINT16_MAX);
2190         nfs->match_len = htons(match_len);
2191         nfs->cookie = fs->cookie;
2192         nfs->packet_count = htonll(fs->packet_count);
2193         nfs->byte_count = htonll(fs->byte_count);
2194     } else {
2195         NOT_REACHED();
2196     }
2197
2198     ofputil_postappend_stats_reply(start_ofs, replies);
2199 }
2200
2201 /* Converts abstract ofputil_aggregate_stats 'stats' into an OFPST_AGGREGATE or
2202  * NXST_AGGREGATE reply according to 'protocol', and returns the message. */
2203 struct ofpbuf *
2204 ofputil_encode_aggregate_stats_reply(
2205     const struct ofputil_aggregate_stats *stats,
2206     const struct ofp_stats_msg *request)
2207 {
2208     struct ofpbuf *msg;
2209
2210     if (request->type == htons(OFPST_AGGREGATE)) {
2211         struct ofp_aggregate_stats_reply *asr;
2212
2213         asr = ofputil_make_stats_reply(sizeof *asr, request, &msg);
2214         put_32aligned_be64(&asr->packet_count,
2215                            htonll(unknown_to_zero(stats->packet_count)));
2216         put_32aligned_be64(&asr->byte_count,
2217                            htonll(unknown_to_zero(stats->byte_count)));
2218         asr->flow_count = htonl(stats->flow_count);
2219     } else if (request->type == htons(OFPST_VENDOR)) {
2220         struct nx_aggregate_stats_reply *nasr;
2221
2222         nasr = ofputil_make_stats_reply(sizeof *nasr, request, &msg);
2223         assert(nasr->nsm.subtype == htonl(NXST_AGGREGATE));
2224         nasr->packet_count = htonll(stats->packet_count);
2225         nasr->byte_count = htonll(stats->byte_count);
2226         nasr->flow_count = htonl(stats->flow_count);
2227     } else {
2228         NOT_REACHED();
2229     }
2230
2231     return msg;
2232 }
2233
2234 /* Converts an OFPT_FLOW_REMOVED or NXT_FLOW_REMOVED message 'oh' into an
2235  * abstract ofputil_flow_removed in 'fr'.  Returns 0 if successful, otherwise
2236  * an OpenFlow error code. */
2237 enum ofperr
2238 ofputil_decode_flow_removed(struct ofputil_flow_removed *fr,
2239                             const struct ofp_header *oh)
2240 {
2241     const struct ofputil_msg_type *type;
2242     enum ofputil_msg_code code;
2243
2244     ofputil_decode_msg_type(oh, &type);
2245     code = ofputil_msg_type_code(type);
2246     if (code == OFPUTIL_OFPT_FLOW_REMOVED) {
2247         const struct ofp_flow_removed *ofr;
2248
2249         ofr = (const struct ofp_flow_removed *) oh;
2250         ofputil_cls_rule_from_ofp10_match(&ofr->match, ntohs(ofr->priority),
2251                                           &fr->rule);
2252         fr->cookie = ofr->cookie;
2253         fr->reason = ofr->reason;
2254         fr->duration_sec = ntohl(ofr->duration_sec);
2255         fr->duration_nsec = ntohl(ofr->duration_nsec);
2256         fr->idle_timeout = ntohs(ofr->idle_timeout);
2257         fr->packet_count = ntohll(ofr->packet_count);
2258         fr->byte_count = ntohll(ofr->byte_count);
2259     } else if (code == OFPUTIL_NXT_FLOW_REMOVED) {
2260         struct nx_flow_removed *nfr;
2261         struct ofpbuf b;
2262         int error;
2263
2264         ofpbuf_use_const(&b, oh, ntohs(oh->length));
2265
2266         nfr = ofpbuf_pull(&b, sizeof *nfr);
2267         error = nx_pull_match(&b, ntohs(nfr->match_len), ntohs(nfr->priority),
2268                               &fr->rule, NULL, NULL);
2269         if (error) {
2270             return error;
2271         }
2272         if (b.size) {
2273             return OFPERR_OFPBRC_BAD_LEN;
2274         }
2275
2276         fr->cookie = nfr->cookie;
2277         fr->reason = nfr->reason;
2278         fr->duration_sec = ntohl(nfr->duration_sec);
2279         fr->duration_nsec = ntohl(nfr->duration_nsec);
2280         fr->idle_timeout = ntohs(nfr->idle_timeout);
2281         fr->packet_count = ntohll(nfr->packet_count);
2282         fr->byte_count = ntohll(nfr->byte_count);
2283     } else {
2284         NOT_REACHED();
2285     }
2286
2287     return 0;
2288 }
2289
2290 /* Converts abstract ofputil_flow_removed 'fr' into an OFPT_FLOW_REMOVED or
2291  * NXT_FLOW_REMOVED message 'oh' according to 'protocol', and returns the
2292  * message. */
2293 struct ofpbuf *
2294 ofputil_encode_flow_removed(const struct ofputil_flow_removed *fr,
2295                             enum ofputil_protocol protocol)
2296 {
2297     struct ofpbuf *msg;
2298
2299     switch (protocol) {
2300     case OFPUTIL_P_OF10:
2301     case OFPUTIL_P_OF10_TID: {
2302         struct ofp_flow_removed *ofr;
2303
2304         ofr = make_openflow_xid(sizeof *ofr, OFPT_FLOW_REMOVED, htonl(0),
2305                                 &msg);
2306         ofputil_cls_rule_to_ofp10_match(&fr->rule, &ofr->match);
2307         ofr->cookie = fr->cookie;
2308         ofr->priority = htons(fr->rule.priority);
2309         ofr->reason = fr->reason;
2310         ofr->duration_sec = htonl(fr->duration_sec);
2311         ofr->duration_nsec = htonl(fr->duration_nsec);
2312         ofr->idle_timeout = htons(fr->idle_timeout);
2313         ofr->packet_count = htonll(unknown_to_zero(fr->packet_count));
2314         ofr->byte_count = htonll(unknown_to_zero(fr->byte_count));
2315         break;
2316     }
2317
2318     case OFPUTIL_P_NXM:
2319     case OFPUTIL_P_NXM_TID: {
2320         struct nx_flow_removed *nfr;
2321         int match_len;
2322
2323         make_nxmsg_xid(sizeof *nfr, NXT_FLOW_REMOVED, htonl(0), &msg);
2324         match_len = nx_put_match(msg, false, &fr->rule, 0, 0);
2325
2326         nfr = msg->data;
2327         nfr->cookie = fr->cookie;
2328         nfr->priority = htons(fr->rule.priority);
2329         nfr->reason = fr->reason;
2330         nfr->duration_sec = htonl(fr->duration_sec);
2331         nfr->duration_nsec = htonl(fr->duration_nsec);
2332         nfr->idle_timeout = htons(fr->idle_timeout);
2333         nfr->match_len = htons(match_len);
2334         nfr->packet_count = htonll(fr->packet_count);
2335         nfr->byte_count = htonll(fr->byte_count);
2336         break;
2337     }
2338
2339     default:
2340         NOT_REACHED();
2341     }
2342
2343     return msg;
2344 }
2345
2346 enum ofperr
2347 ofputil_decode_packet_in(struct ofputil_packet_in *pin,
2348                          const struct ofp_header *oh)
2349 {
2350     const struct ofputil_msg_type *type;
2351     enum ofputil_msg_code code;
2352
2353     ofputil_decode_msg_type(oh, &type);
2354     code = ofputil_msg_type_code(type);
2355     memset(pin, 0, sizeof *pin);
2356
2357     if (code == OFPUTIL_OFPT_PACKET_IN) {
2358         const struct ofp_packet_in *opi = (const struct ofp_packet_in *) oh;
2359
2360         pin->packet = opi->data;
2361         pin->packet_len = ntohs(opi->header.length)
2362             - offsetof(struct ofp_packet_in, data);
2363
2364         pin->fmd.in_port = ntohs(opi->in_port);
2365         pin->reason = opi->reason;
2366         pin->buffer_id = ntohl(opi->buffer_id);
2367         pin->total_len = ntohs(opi->total_len);
2368     } else if (code == OFPUTIL_NXT_PACKET_IN) {
2369         const struct nx_packet_in *npi;
2370         struct cls_rule rule;
2371         struct ofpbuf b;
2372         int error;
2373
2374         ofpbuf_use_const(&b, oh, ntohs(oh->length));
2375
2376         npi = ofpbuf_pull(&b, sizeof *npi);
2377         error = nx_pull_match_loose(&b, ntohs(npi->match_len), 0, &rule, NULL,
2378                                     NULL);
2379         if (error) {
2380             return error;
2381         }
2382
2383         if (!ofpbuf_try_pull(&b, 2)) {
2384             return OFPERR_OFPBRC_BAD_LEN;
2385         }
2386
2387         pin->packet = b.data;
2388         pin->packet_len = b.size;
2389         pin->reason = npi->reason;
2390         pin->table_id = npi->table_id;
2391         pin->cookie = npi->cookie;
2392
2393         pin->fmd.in_port = rule.flow.in_port;
2394
2395         pin->fmd.tun_id = rule.flow.tun_id;
2396         pin->fmd.tun_id_mask = rule.wc.tun_id_mask;
2397
2398         pin->fmd.metadata = rule.flow.metadata;
2399         pin->fmd.metadata_mask = rule.wc.metadata_mask;
2400
2401         memcpy(pin->fmd.regs, rule.flow.regs, sizeof pin->fmd.regs);
2402         memcpy(pin->fmd.reg_masks, rule.wc.reg_masks,
2403                sizeof pin->fmd.reg_masks);
2404
2405         pin->buffer_id = ntohl(npi->buffer_id);
2406         pin->total_len = ntohs(npi->total_len);
2407     } else {
2408         NOT_REACHED();
2409     }
2410
2411     return 0;
2412 }
2413
2414 /* Converts abstract ofputil_packet_in 'pin' into a PACKET_IN message
2415  * in the format specified by 'packet_in_format'.  */
2416 struct ofpbuf *
2417 ofputil_encode_packet_in(const struct ofputil_packet_in *pin,
2418                          enum nx_packet_in_format packet_in_format)
2419 {
2420     size_t send_len = MIN(pin->send_len, pin->packet_len);
2421     struct ofpbuf *packet;
2422
2423     /* Add OFPT_PACKET_IN. */
2424     if (packet_in_format == NXPIF_OPENFLOW10) {
2425         size_t header_len = offsetof(struct ofp_packet_in, data);
2426         struct ofp_packet_in *opi;
2427
2428         packet = ofpbuf_new(send_len + header_len);
2429         opi = ofpbuf_put_zeros(packet, header_len);
2430         opi->header.version = OFP10_VERSION;
2431         opi->header.type = OFPT_PACKET_IN;
2432         opi->total_len = htons(pin->total_len);
2433         opi->in_port = htons(pin->fmd.in_port);
2434         opi->reason = pin->reason;
2435         opi->buffer_id = htonl(pin->buffer_id);
2436
2437         ofpbuf_put(packet, pin->packet, send_len);
2438     } else if (packet_in_format == NXPIF_NXM) {
2439         struct nx_packet_in *npi;
2440         struct cls_rule rule;
2441         size_t match_len;
2442         size_t i;
2443
2444         /* Estimate of required PACKET_IN length includes the NPI header, space
2445          * for the match (2 times sizeof the metadata seems like enough), 2
2446          * bytes for padding, and the packet length. */
2447         packet = ofpbuf_new(sizeof *npi + sizeof(struct flow_metadata) * 2
2448                             + 2 + send_len);
2449
2450         cls_rule_init_catchall(&rule, 0);
2451         cls_rule_set_tun_id_masked(&rule, pin->fmd.tun_id,
2452                                    pin->fmd.tun_id_mask);
2453         cls_rule_set_metadata_masked(&rule, pin->fmd.metadata,
2454                                    pin->fmd.metadata_mask);
2455
2456
2457         for (i = 0; i < FLOW_N_REGS; i++) {
2458             cls_rule_set_reg_masked(&rule, i, pin->fmd.regs[i],
2459                                     pin->fmd.reg_masks[i]);
2460         }
2461
2462         cls_rule_set_in_port(&rule, pin->fmd.in_port);
2463
2464         ofpbuf_put_zeros(packet, sizeof *npi);
2465         match_len = nx_put_match(packet, false, &rule, 0, 0);
2466         ofpbuf_put_zeros(packet, 2);
2467         ofpbuf_put(packet, pin->packet, send_len);
2468
2469         npi = packet->data;
2470         npi->nxh.header.version = OFP10_VERSION;
2471         npi->nxh.header.type = OFPT_VENDOR;
2472         npi->nxh.vendor = htonl(NX_VENDOR_ID);
2473         npi->nxh.subtype = htonl(NXT_PACKET_IN);
2474
2475         npi->buffer_id = htonl(pin->buffer_id);
2476         npi->total_len = htons(pin->total_len);
2477         npi->reason = pin->reason;
2478         npi->table_id = pin->table_id;
2479         npi->cookie = pin->cookie;
2480         npi->match_len = htons(match_len);
2481     } else {
2482         NOT_REACHED();
2483     }
2484     update_openflow_length(packet);
2485
2486     return packet;
2487 }
2488
2489 const char *
2490 ofputil_packet_in_reason_to_string(enum ofp_packet_in_reason reason)
2491 {
2492     static char s[INT_STRLEN(int) + 1];
2493
2494     switch (reason) {
2495     case OFPR_NO_MATCH:
2496         return "no_match";
2497     case OFPR_ACTION:
2498         return "action";
2499     case OFPR_INVALID_TTL:
2500         return "invalid_ttl";
2501
2502     case OFPR_N_REASONS:
2503     default:
2504         sprintf(s, "%d", (int) reason);
2505         return s;
2506     }
2507 }
2508
2509 bool
2510 ofputil_packet_in_reason_from_string(const char *s,
2511                                      enum ofp_packet_in_reason *reason)
2512 {
2513     int i;
2514
2515     for (i = 0; i < OFPR_N_REASONS; i++) {
2516         if (!strcasecmp(s, ofputil_packet_in_reason_to_string(i))) {
2517             *reason = i;
2518             return true;
2519         }
2520     }
2521     return false;
2522 }
2523
2524 /* Converts an OFPT_PACKET_OUT in 'opo' into an abstract ofputil_packet_out in
2525  * 'po'.
2526  *
2527  * Uses 'ofpacts' to store the abstract OFPACT_* version of the packet out
2528  * message's actions.  The caller must initialize 'ofpacts' and retains
2529  * ownership of it.  'po->ofpacts' will point into the 'ofpacts' buffer.
2530  *
2531  * Returns 0 if successful, otherwise an OFPERR_* value. */
2532 enum ofperr
2533 ofputil_decode_packet_out(struct ofputil_packet_out *po,
2534                           const struct ofp_packet_out *opo,
2535                           struct ofpbuf *ofpacts)
2536 {
2537     enum ofperr error;
2538     struct ofpbuf b;
2539
2540     po->buffer_id = ntohl(opo->buffer_id);
2541     po->in_port = ntohs(opo->in_port);
2542     if (po->in_port >= OFPP_MAX && po->in_port != OFPP_LOCAL
2543         && po->in_port != OFPP_NONE && po->in_port != OFPP_CONTROLLER) {
2544         VLOG_WARN_RL(&bad_ofmsg_rl, "packet-out has bad input port %#"PRIx16,
2545                      po->in_port);
2546         return OFPERR_NXBRC_BAD_IN_PORT;
2547     }
2548
2549     ofpbuf_use_const(&b, opo, ntohs(opo->header.length));
2550     ofpbuf_pull(&b, sizeof *opo);
2551
2552     error = ofpacts_pull_openflow10(&b, ntohs(opo->actions_len), ofpacts);
2553     if (error) {
2554         return error;
2555     }
2556     po->ofpacts = ofpacts->data;
2557     po->ofpacts_len = ofpacts->size;
2558
2559     if (po->buffer_id == UINT32_MAX) {
2560         po->packet = b.data;
2561         po->packet_len = b.size;
2562     } else {
2563         po->packet = NULL;
2564         po->packet_len = 0;
2565     }
2566
2567     return 0;
2568 }
2569 \f
2570 /* ofputil_phy_port */
2571
2572 /* NETDEV_F_* to and from OFPPF_* and OFPPF10_*. */
2573 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_HD    == OFPPF_10MB_HD);  /* bit 0 */
2574 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_FD    == OFPPF_10MB_FD);  /* bit 1 */
2575 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_HD   == OFPPF_100MB_HD); /* bit 2 */
2576 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_FD   == OFPPF_100MB_FD); /* bit 3 */
2577 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_HD     == OFPPF_1GB_HD);   /* bit 4 */
2578 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_FD     == OFPPF_1GB_FD);   /* bit 5 */
2579 BUILD_ASSERT_DECL((int) NETDEV_F_10GB_FD    == OFPPF_10GB_FD);  /* bit 6 */
2580
2581 /* NETDEV_F_ bits 11...15 are OFPPF10_ bits 7...11: */
2582 BUILD_ASSERT_DECL((int) NETDEV_F_COPPER == (OFPPF10_COPPER << 4));
2583 BUILD_ASSERT_DECL((int) NETDEV_F_FIBER == (OFPPF10_FIBER << 4));
2584 BUILD_ASSERT_DECL((int) NETDEV_F_AUTONEG == (OFPPF10_AUTONEG << 4));
2585 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE == (OFPPF10_PAUSE << 4));
2586 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE_ASYM == (OFPPF10_PAUSE_ASYM << 4));
2587
2588 static enum netdev_features
2589 netdev_port_features_from_ofp10(ovs_be32 ofp10_)
2590 {
2591     uint32_t ofp10 = ntohl(ofp10_);
2592     return (ofp10 & 0x7f) | ((ofp10 & 0xf80) << 4);
2593 }
2594
2595 static ovs_be32
2596 netdev_port_features_to_ofp10(enum netdev_features features)
2597 {
2598     return htonl((features & 0x7f) | ((features & 0xf800) >> 4));
2599 }
2600
2601 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_HD    == OFPPF_10MB_HD);     /* bit 0 */
2602 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_FD    == OFPPF_10MB_FD);     /* bit 1 */
2603 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_HD   == OFPPF_100MB_HD);    /* bit 2 */
2604 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_FD   == OFPPF_100MB_FD);    /* bit 3 */
2605 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_HD     == OFPPF_1GB_HD);      /* bit 4 */
2606 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_FD     == OFPPF_1GB_FD);      /* bit 5 */
2607 BUILD_ASSERT_DECL((int) NETDEV_F_10GB_FD    == OFPPF_10GB_FD);     /* bit 6 */
2608 BUILD_ASSERT_DECL((int) NETDEV_F_40GB_FD    == OFPPF11_40GB_FD);   /* bit 7 */
2609 BUILD_ASSERT_DECL((int) NETDEV_F_100GB_FD   == OFPPF11_100GB_FD);  /* bit 8 */
2610 BUILD_ASSERT_DECL((int) NETDEV_F_1TB_FD     == OFPPF11_1TB_FD);    /* bit 9 */
2611 BUILD_ASSERT_DECL((int) NETDEV_F_OTHER      == OFPPF11_OTHER);     /* bit 10 */
2612 BUILD_ASSERT_DECL((int) NETDEV_F_COPPER     == OFPPF11_COPPER);    /* bit 11 */
2613 BUILD_ASSERT_DECL((int) NETDEV_F_FIBER      == OFPPF11_FIBER);     /* bit 12 */
2614 BUILD_ASSERT_DECL((int) NETDEV_F_AUTONEG    == OFPPF11_AUTONEG);   /* bit 13 */
2615 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE      == OFPPF11_PAUSE);     /* bit 14 */
2616 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE_ASYM == OFPPF11_PAUSE_ASYM);/* bit 15 */
2617
2618 static enum netdev_features
2619 netdev_port_features_from_ofp11(ovs_be32 ofp11)
2620 {
2621     return ntohl(ofp11) & 0xffff;
2622 }
2623
2624 static ovs_be32
2625 netdev_port_features_to_ofp11(enum netdev_features features)
2626 {
2627     return htonl(features & 0xffff);
2628 }
2629
2630 static enum ofperr
2631 ofputil_decode_ofp10_phy_port(struct ofputil_phy_port *pp,
2632                               const struct ofp10_phy_port *opp)
2633 {
2634     memset(pp, 0, sizeof *pp);
2635
2636     pp->port_no = ntohs(opp->port_no);
2637     memcpy(pp->hw_addr, opp->hw_addr, OFP_ETH_ALEN);
2638     ovs_strlcpy(pp->name, opp->name, OFP_MAX_PORT_NAME_LEN);
2639
2640     pp->config = ntohl(opp->config) & OFPPC10_ALL;
2641     pp->state = ntohl(opp->state) & OFPPS10_ALL;
2642
2643     pp->curr = netdev_port_features_from_ofp10(opp->curr);
2644     pp->advertised = netdev_port_features_from_ofp10(opp->advertised);
2645     pp->supported = netdev_port_features_from_ofp10(opp->supported);
2646     pp->peer = netdev_port_features_from_ofp10(opp->peer);
2647
2648     pp->curr_speed = netdev_features_to_bps(pp->curr) / 1000;
2649     pp->max_speed = netdev_features_to_bps(pp->supported) / 1000;
2650
2651     return 0;
2652 }
2653
2654 static enum ofperr
2655 ofputil_decode_ofp11_port(struct ofputil_phy_port *pp,
2656                           const struct ofp11_port *op)
2657 {
2658     enum ofperr error;
2659
2660     memset(pp, 0, sizeof *pp);
2661
2662     error = ofputil_port_from_ofp11(op->port_no, &pp->port_no);
2663     if (error) {
2664         return error;
2665     }
2666     memcpy(pp->hw_addr, op->hw_addr, OFP_ETH_ALEN);
2667     ovs_strlcpy(pp->name, op->name, OFP_MAX_PORT_NAME_LEN);
2668
2669     pp->config = ntohl(op->config) & OFPPC11_ALL;
2670     pp->state = ntohl(op->state) & OFPPC11_ALL;
2671
2672     pp->curr = netdev_port_features_from_ofp11(op->curr);
2673     pp->advertised = netdev_port_features_from_ofp11(op->advertised);
2674     pp->supported = netdev_port_features_from_ofp11(op->supported);
2675     pp->peer = netdev_port_features_from_ofp11(op->peer);
2676
2677     pp->curr_speed = ntohl(op->curr_speed);
2678     pp->max_speed = ntohl(op->max_speed);
2679
2680     return 0;
2681 }
2682
2683 static size_t
2684 ofputil_get_phy_port_size(uint8_t ofp_version)
2685 {
2686     return ofp_version == OFP10_VERSION ? sizeof(struct ofp10_phy_port)
2687                                         : sizeof(struct ofp11_port);
2688 }
2689
2690 static void
2691 ofputil_encode_ofp10_phy_port(const struct ofputil_phy_port *pp,
2692                               struct ofp10_phy_port *opp)
2693 {
2694     memset(opp, 0, sizeof *opp);
2695
2696     opp->port_no = htons(pp->port_no);
2697     memcpy(opp->hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2698     ovs_strlcpy(opp->name, pp->name, OFP_MAX_PORT_NAME_LEN);
2699
2700     opp->config = htonl(pp->config & OFPPC10_ALL);
2701     opp->state = htonl(pp->state & OFPPS10_ALL);
2702
2703     opp->curr = netdev_port_features_to_ofp10(pp->curr);
2704     opp->advertised = netdev_port_features_to_ofp10(pp->advertised);
2705     opp->supported = netdev_port_features_to_ofp10(pp->supported);
2706     opp->peer = netdev_port_features_to_ofp10(pp->peer);
2707 }
2708
2709 static void
2710 ofputil_encode_ofp11_port(const struct ofputil_phy_port *pp,
2711                           struct ofp11_port *op)
2712 {
2713     memset(op, 0, sizeof *op);
2714
2715     op->port_no = ofputil_port_to_ofp11(pp->port_no);
2716     memcpy(op->hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2717     ovs_strlcpy(op->name, pp->name, OFP_MAX_PORT_NAME_LEN);
2718
2719     op->config = htonl(pp->config & OFPPC11_ALL);
2720     op->state = htonl(pp->state & OFPPS11_ALL);
2721
2722     op->curr = netdev_port_features_to_ofp11(pp->curr);
2723     op->advertised = netdev_port_features_to_ofp11(pp->advertised);
2724     op->supported = netdev_port_features_to_ofp11(pp->supported);
2725     op->peer = netdev_port_features_to_ofp11(pp->peer);
2726
2727     op->curr_speed = htonl(pp->curr_speed);
2728     op->max_speed = htonl(pp->max_speed);
2729 }
2730
2731 static void
2732 ofputil_put_phy_port(uint8_t ofp_version, const struct ofputil_phy_port *pp,
2733                      struct ofpbuf *b)
2734 {
2735     if (ofp_version == OFP10_VERSION) {
2736         struct ofp10_phy_port *opp;
2737         if (b->size + sizeof *opp <= UINT16_MAX) {
2738             opp = ofpbuf_put_uninit(b, sizeof *opp);
2739             ofputil_encode_ofp10_phy_port(pp, opp);
2740         }
2741     } else {
2742         struct ofp11_port *op;
2743         if (b->size + sizeof *op <= UINT16_MAX) {
2744             op = ofpbuf_put_uninit(b, sizeof *op);
2745             ofputil_encode_ofp11_port(pp, op);
2746         }
2747     }
2748 }
2749
2750 void
2751 ofputil_append_port_desc_stats_reply(uint8_t ofp_version,
2752                                      const struct ofputil_phy_port *pp,
2753                                      struct list *replies)
2754 {
2755     if (ofp_version == OFP10_VERSION) {
2756         struct ofp10_phy_port *opp;
2757
2758         opp = ofputil_append_stats_reply(sizeof *opp, replies);
2759         ofputil_encode_ofp10_phy_port(pp, opp);
2760     } else {
2761         struct ofp11_port *op;
2762
2763         op = ofputil_append_stats_reply(sizeof *op, replies);
2764         ofputil_encode_ofp11_port(pp, op);
2765     }
2766 }
2767 \f
2768 /* ofputil_switch_features */
2769
2770 #define OFPC_COMMON (OFPC_FLOW_STATS | OFPC_TABLE_STATS | OFPC_PORT_STATS | \
2771                      OFPC_IP_REASM | OFPC_QUEUE_STATS | OFPC_ARP_MATCH_IP)
2772 BUILD_ASSERT_DECL((int) OFPUTIL_C_FLOW_STATS == OFPC_FLOW_STATS);
2773 BUILD_ASSERT_DECL((int) OFPUTIL_C_TABLE_STATS == OFPC_TABLE_STATS);
2774 BUILD_ASSERT_DECL((int) OFPUTIL_C_PORT_STATS == OFPC_PORT_STATS);
2775 BUILD_ASSERT_DECL((int) OFPUTIL_C_IP_REASM == OFPC_IP_REASM);
2776 BUILD_ASSERT_DECL((int) OFPUTIL_C_QUEUE_STATS == OFPC_QUEUE_STATS);
2777 BUILD_ASSERT_DECL((int) OFPUTIL_C_ARP_MATCH_IP == OFPC_ARP_MATCH_IP);
2778
2779 struct ofputil_action_bit_translation {
2780     enum ofputil_action_bitmap ofputil_bit;
2781     int of_bit;
2782 };
2783
2784 static const struct ofputil_action_bit_translation of10_action_bits[] = {
2785     { OFPUTIL_A_OUTPUT,       OFPAT10_OUTPUT },
2786     { OFPUTIL_A_SET_VLAN_VID, OFPAT10_SET_VLAN_VID },
2787     { OFPUTIL_A_SET_VLAN_PCP, OFPAT10_SET_VLAN_PCP },
2788     { OFPUTIL_A_STRIP_VLAN,   OFPAT10_STRIP_VLAN },
2789     { OFPUTIL_A_SET_DL_SRC,   OFPAT10_SET_DL_SRC },
2790     { OFPUTIL_A_SET_DL_DST,   OFPAT10_SET_DL_DST },
2791     { OFPUTIL_A_SET_NW_SRC,   OFPAT10_SET_NW_SRC },
2792     { OFPUTIL_A_SET_NW_DST,   OFPAT10_SET_NW_DST },
2793     { OFPUTIL_A_SET_NW_TOS,   OFPAT10_SET_NW_TOS },
2794     { OFPUTIL_A_SET_TP_SRC,   OFPAT10_SET_TP_SRC },
2795     { OFPUTIL_A_SET_TP_DST,   OFPAT10_SET_TP_DST },
2796     { OFPUTIL_A_ENQUEUE,      OFPAT10_ENQUEUE },
2797     { 0, 0 },
2798 };
2799
2800 static const struct ofputil_action_bit_translation of11_action_bits[] = {
2801     { OFPUTIL_A_OUTPUT,         OFPAT11_OUTPUT },
2802     { OFPUTIL_A_SET_VLAN_VID,   OFPAT11_SET_VLAN_VID },
2803     { OFPUTIL_A_SET_VLAN_PCP,   OFPAT11_SET_VLAN_PCP },
2804     { OFPUTIL_A_SET_DL_SRC,     OFPAT11_SET_DL_SRC },
2805     { OFPUTIL_A_SET_DL_DST,     OFPAT11_SET_DL_DST },
2806     { OFPUTIL_A_SET_NW_SRC,     OFPAT11_SET_NW_SRC },
2807     { OFPUTIL_A_SET_NW_DST,     OFPAT11_SET_NW_DST },
2808     { OFPUTIL_A_SET_NW_TOS,     OFPAT11_SET_NW_TOS },
2809     { OFPUTIL_A_SET_NW_ECN,     OFPAT11_SET_NW_ECN },
2810     { OFPUTIL_A_SET_TP_SRC,     OFPAT11_SET_TP_SRC },
2811     { OFPUTIL_A_SET_TP_DST,     OFPAT11_SET_TP_DST },
2812     { OFPUTIL_A_COPY_TTL_OUT,   OFPAT11_COPY_TTL_OUT },
2813     { OFPUTIL_A_COPY_TTL_IN,    OFPAT11_COPY_TTL_IN },
2814     { OFPUTIL_A_SET_MPLS_LABEL, OFPAT11_SET_MPLS_LABEL },
2815     { OFPUTIL_A_SET_MPLS_TC,    OFPAT11_SET_MPLS_TC },
2816     { OFPUTIL_A_SET_MPLS_TTL,   OFPAT11_SET_MPLS_TTL },
2817     { OFPUTIL_A_DEC_MPLS_TTL,   OFPAT11_DEC_MPLS_TTL },
2818     { OFPUTIL_A_PUSH_VLAN,      OFPAT11_PUSH_VLAN },
2819     { OFPUTIL_A_POP_VLAN,       OFPAT11_POP_VLAN },
2820     { OFPUTIL_A_PUSH_MPLS,      OFPAT11_PUSH_MPLS },
2821     { OFPUTIL_A_POP_MPLS,       OFPAT11_POP_MPLS },
2822     { OFPUTIL_A_SET_QUEUE,      OFPAT11_SET_QUEUE },
2823     { OFPUTIL_A_GROUP,          OFPAT11_GROUP },
2824     { OFPUTIL_A_SET_NW_TTL,     OFPAT11_SET_NW_TTL },
2825     { OFPUTIL_A_DEC_NW_TTL,     OFPAT11_DEC_NW_TTL },
2826     { 0, 0 },
2827 };
2828
2829 static enum ofputil_action_bitmap
2830 decode_action_bits(ovs_be32 of_actions,
2831                    const struct ofputil_action_bit_translation *x)
2832 {
2833     enum ofputil_action_bitmap ofputil_actions;
2834
2835     ofputil_actions = 0;
2836     for (; x->ofputil_bit; x++) {
2837         if (of_actions & htonl(1u << x->of_bit)) {
2838             ofputil_actions |= x->ofputil_bit;
2839         }
2840     }
2841     return ofputil_actions;
2842 }
2843
2844 /* Decodes an OpenFlow 1.0 or 1.1 "switch_features" structure 'osf' into an
2845  * abstract representation in '*features'.  Initializes '*b' to iterate over
2846  * the OpenFlow port structures following 'osf' with later calls to
2847  * ofputil_pull_phy_port().  Returns 0 if successful, otherwise an
2848  * OFPERR_* value.  */
2849 enum ofperr
2850 ofputil_decode_switch_features(const struct ofp_switch_features *osf,
2851                                struct ofputil_switch_features *features,
2852                                struct ofpbuf *b)
2853 {
2854     ofpbuf_use_const(b, osf, ntohs(osf->header.length));
2855     ofpbuf_pull(b, sizeof *osf);
2856
2857     features->datapath_id = ntohll(osf->datapath_id);
2858     features->n_buffers = ntohl(osf->n_buffers);
2859     features->n_tables = osf->n_tables;
2860
2861     features->capabilities = ntohl(osf->capabilities) & OFPC_COMMON;
2862
2863     if (b->size % ofputil_get_phy_port_size(osf->header.version)) {
2864         return OFPERR_OFPBRC_BAD_LEN;
2865     }
2866
2867     if (osf->header.version == OFP10_VERSION) {
2868         if (osf->capabilities & htonl(OFPC10_STP)) {
2869             features->capabilities |= OFPUTIL_C_STP;
2870         }
2871         features->actions = decode_action_bits(osf->actions, of10_action_bits);
2872     } else if (osf->header.version == OFP11_VERSION) {
2873         if (osf->capabilities & htonl(OFPC11_GROUP_STATS)) {
2874             features->capabilities |= OFPUTIL_C_GROUP_STATS;
2875         }
2876         features->actions = decode_action_bits(osf->actions, of11_action_bits);
2877     } else {
2878         return OFPERR_OFPBRC_BAD_VERSION;
2879     }
2880
2881     return 0;
2882 }
2883
2884 /* Returns true if the maximum number of ports are in 'osf'. */
2885 static bool
2886 max_ports_in_features(const struct ofp_switch_features *osf)
2887 {
2888     size_t pp_size = ofputil_get_phy_port_size(osf->header.version);
2889     return ntohs(osf->header.length) + pp_size > UINT16_MAX;
2890 }
2891
2892 /* Given a buffer 'b' that contains a Features Reply message, checks if
2893  * it contains the maximum number of ports that will fit.  If so, it
2894  * returns true and removes the ports from the message.  The caller
2895  * should then send an OFPST_PORT_DESC stats request to get the ports,
2896  * since the switch may have more ports than could be represented in the
2897  * Features Reply.  Otherwise, returns false.
2898  */
2899 bool
2900 ofputil_switch_features_ports_trunc(struct ofpbuf *b)
2901 {
2902     struct ofp_switch_features *osf = b->data;
2903
2904     if (max_ports_in_features(osf)) {
2905         /* Remove all the ports. */
2906         b->size = sizeof(*osf);
2907         update_openflow_length(b);
2908
2909         return true;
2910     }
2911
2912     return false;
2913 }
2914
2915 static ovs_be32
2916 encode_action_bits(enum ofputil_action_bitmap ofputil_actions,
2917                    const struct ofputil_action_bit_translation *x)
2918 {
2919     uint32_t of_actions;
2920
2921     of_actions = 0;
2922     for (; x->ofputil_bit; x++) {
2923         if (ofputil_actions & x->ofputil_bit) {
2924             of_actions |= 1 << x->of_bit;
2925         }
2926     }
2927     return htonl(of_actions);
2928 }
2929
2930 /* Returns a buffer owned by the caller that encodes 'features' in the format
2931  * required by 'protocol' with the given 'xid'.  The caller should append port
2932  * information to the buffer with subsequent calls to
2933  * ofputil_put_switch_features_port(). */
2934 struct ofpbuf *
2935 ofputil_encode_switch_features(const struct ofputil_switch_features *features,
2936                                enum ofputil_protocol protocol, ovs_be32 xid)
2937 {
2938     struct ofp_switch_features *osf;
2939     struct ofpbuf *b;
2940
2941     osf = make_openflow_xid(sizeof *osf, OFPT_FEATURES_REPLY, xid, &b);
2942     osf->header.version = ofputil_protocol_to_ofp_version(protocol);
2943     osf->datapath_id = htonll(features->datapath_id);
2944     osf->n_buffers = htonl(features->n_buffers);
2945     osf->n_tables = features->n_tables;
2946
2947     osf->capabilities = htonl(features->capabilities & OFPC_COMMON);
2948     if (osf->header.version == OFP10_VERSION) {
2949         if (features->capabilities & OFPUTIL_C_STP) {
2950             osf->capabilities |= htonl(OFPC10_STP);
2951         }
2952         osf->actions = encode_action_bits(features->actions, of10_action_bits);
2953     } else {
2954         if (features->capabilities & OFPUTIL_C_GROUP_STATS) {
2955             osf->capabilities |= htonl(OFPC11_GROUP_STATS);
2956         }
2957         osf->actions = encode_action_bits(features->actions, of11_action_bits);
2958     }
2959
2960     return b;
2961 }
2962
2963 /* Encodes 'pp' into the format required by the switch_features message already
2964  * in 'b', which should have been returned by ofputil_encode_switch_features(),
2965  * and appends the encoded version to 'b'. */
2966 void
2967 ofputil_put_switch_features_port(const struct ofputil_phy_port *pp,
2968                                  struct ofpbuf *b)
2969 {
2970     const struct ofp_switch_features *osf = b->data;
2971
2972     ofputil_put_phy_port(osf->header.version, pp, b);
2973 }
2974 \f
2975 /* ofputil_port_status */
2976
2977 /* Decodes the OpenFlow "port status" message in '*ops' into an abstract form
2978  * in '*ps'.  Returns 0 if successful, otherwise an OFPERR_* value. */
2979 enum ofperr
2980 ofputil_decode_port_status(const struct ofp_port_status *ops,
2981                            struct ofputil_port_status *ps)
2982 {
2983     struct ofpbuf b;
2984     int retval;
2985
2986     if (ops->reason != OFPPR_ADD &&
2987         ops->reason != OFPPR_DELETE &&
2988         ops->reason != OFPPR_MODIFY) {
2989         return OFPERR_NXBRC_BAD_REASON;
2990     }
2991     ps->reason = ops->reason;
2992
2993     ofpbuf_use_const(&b, ops, ntohs(ops->header.length));
2994     ofpbuf_pull(&b, sizeof *ops);
2995     retval = ofputil_pull_phy_port(ops->header.version, &b, &ps->desc);
2996     assert(retval != EOF);
2997     return retval;
2998 }
2999
3000 /* Converts the abstract form of a "port status" message in '*ps' into an
3001  * OpenFlow message suitable for 'protocol', and returns that encoded form in
3002  * a buffer owned by the caller. */
3003 struct ofpbuf *
3004 ofputil_encode_port_status(const struct ofputil_port_status *ps,
3005                            enum ofputil_protocol protocol)
3006 {
3007     struct ofp_port_status *ops;
3008     struct ofpbuf *b;
3009
3010     b = ofpbuf_new(sizeof *ops + sizeof(struct ofp11_port));
3011     ops = put_openflow_xid(sizeof *ops, OFPT_PORT_STATUS, htonl(0), b);
3012     ops->header.version = ofputil_protocol_to_ofp_version(protocol);
3013     ops->reason = ps->reason;
3014     ofputil_put_phy_port(ops->header.version, &ps->desc, b);
3015     update_openflow_length(b);
3016     return b;
3017 }
3018 \f
3019 /* ofputil_port_mod */
3020
3021 /* Decodes the OpenFlow "port mod" message in '*oh' into an abstract form in
3022  * '*pm'.  Returns 0 if successful, otherwise an OFPERR_* value. */
3023 enum ofperr
3024 ofputil_decode_port_mod(const struct ofp_header *oh,
3025                         struct ofputil_port_mod *pm)
3026 {
3027     if (oh->version == OFP10_VERSION) {
3028         const struct ofp10_port_mod *opm = (const struct ofp10_port_mod *) oh;
3029
3030         if (oh->length != htons(sizeof *opm)) {
3031             return OFPERR_OFPBRC_BAD_LEN;
3032         }
3033
3034         pm->port_no = ntohs(opm->port_no);
3035         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
3036         pm->config = ntohl(opm->config) & OFPPC10_ALL;
3037         pm->mask = ntohl(opm->mask) & OFPPC10_ALL;
3038         pm->advertise = netdev_port_features_from_ofp10(opm->advertise);
3039     } else if (oh->version == OFP11_VERSION) {
3040         const struct ofp11_port_mod *opm = (const struct ofp11_port_mod *) oh;
3041         enum ofperr error;
3042
3043         if (oh->length != htons(sizeof *opm)) {
3044             return OFPERR_OFPBRC_BAD_LEN;
3045         }
3046
3047         error = ofputil_port_from_ofp11(opm->port_no, &pm->port_no);
3048         if (error) {
3049             return error;
3050         }
3051
3052         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
3053         pm->config = ntohl(opm->config) & OFPPC11_ALL;
3054         pm->mask = ntohl(opm->mask) & OFPPC11_ALL;
3055         pm->advertise = netdev_port_features_from_ofp11(opm->advertise);
3056     } else {
3057         return OFPERR_OFPBRC_BAD_VERSION;
3058     }
3059
3060     pm->config &= pm->mask;
3061     return 0;
3062 }
3063
3064 /* Converts the abstract form of a "port mod" message in '*pm' into an OpenFlow
3065  * message suitable for 'protocol', and returns that encoded form in a buffer
3066  * owned by the caller. */
3067 struct ofpbuf *
3068 ofputil_encode_port_mod(const struct ofputil_port_mod *pm,
3069                         enum ofputil_protocol protocol)
3070 {
3071     uint8_t ofp_version = ofputil_protocol_to_ofp_version(protocol);
3072     struct ofpbuf *b;
3073
3074     if (ofp_version == OFP10_VERSION) {
3075         struct ofp10_port_mod *opm;
3076
3077         opm = make_openflow(sizeof *opm, OFPT10_PORT_MOD, &b);
3078         opm->port_no = htons(pm->port_no);
3079         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
3080         opm->config = htonl(pm->config & OFPPC10_ALL);
3081         opm->mask = htonl(pm->mask & OFPPC10_ALL);
3082         opm->advertise = netdev_port_features_to_ofp10(pm->advertise);
3083     } else if (ofp_version == OFP11_VERSION) {
3084         struct ofp11_port_mod *opm;
3085
3086         opm = make_openflow(sizeof *opm, OFPT11_PORT_MOD, &b);
3087         opm->port_no = htonl(pm->port_no);
3088         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
3089         opm->config = htonl(pm->config & OFPPC11_ALL);
3090         opm->mask = htonl(pm->mask & OFPPC11_ALL);
3091         opm->advertise = netdev_port_features_to_ofp11(pm->advertise);
3092     } else {
3093         NOT_REACHED();
3094     }
3095
3096     return b;
3097 }
3098
3099 struct ofpbuf *
3100 ofputil_encode_packet_out(const struct ofputil_packet_out *po)
3101 {
3102     struct ofp_packet_out *opo;
3103     struct ofpbuf *msg;
3104     size_t size;
3105
3106     size = sizeof *opo + po->ofpacts_len;
3107     if (po->buffer_id == UINT32_MAX) {
3108         size += po->packet_len;
3109     }
3110
3111     msg = ofpbuf_new(size);
3112     put_openflow(sizeof *opo, OFPT_PACKET_OUT, msg);
3113     ofpacts_put_openflow10(po->ofpacts, po->ofpacts_len, msg);
3114
3115     opo = msg->data;
3116     opo->buffer_id = htonl(po->buffer_id);
3117     opo->in_port = htons(po->in_port);
3118     opo->actions_len = htons(msg->size - sizeof *opo);
3119
3120     if (po->buffer_id == UINT32_MAX) {
3121         ofpbuf_put(msg, po->packet, po->packet_len);
3122     }
3123
3124     update_openflow_length(msg);
3125
3126     return msg;
3127 }
3128
3129 /* Returns a string representing the message type of 'type'.  The string is the
3130  * enumeration constant for the type, e.g. "OFPT_HELLO".  For statistics
3131  * messages, the constant is followed by "request" or "reply",
3132  * e.g. "OFPST_AGGREGATE reply". */
3133 const char *
3134 ofputil_msg_type_name(const struct ofputil_msg_type *type)
3135 {
3136     return type->name;
3137 }
3138 \f
3139 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
3140  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
3141  * an arbitrary transaction id.  Allocated bytes beyond the header, if any, are
3142  * zeroed.
3143  *
3144  * The caller is responsible for freeing '*bufferp' when it is no longer
3145  * needed.
3146  *
3147  * The OpenFlow header length is initially set to 'openflow_len'; if the
3148  * message is later extended, the length should be updated with
3149  * update_openflow_length() before sending.
3150  *
3151  * Returns the header. */
3152 void *
3153 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp)
3154 {
3155     *bufferp = ofpbuf_new(openflow_len);
3156     return put_openflow_xid(openflow_len, type, alloc_xid(), *bufferp);
3157 }
3158
3159 /* Similar to make_openflow() but creates a Nicira vendor extension message
3160  * with the specific 'subtype'.  'subtype' should be in host byte order. */
3161 void *
3162 make_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf **bufferp)
3163 {
3164     return make_nxmsg_xid(openflow_len, subtype, alloc_xid(), bufferp);
3165 }
3166
3167 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
3168  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
3169  * transaction id 'xid'.  Allocated bytes beyond the header, if any, are
3170  * zeroed.
3171  *
3172  * The caller is responsible for freeing '*bufferp' when it is no longer
3173  * needed.
3174  *
3175  * The OpenFlow header length is initially set to 'openflow_len'; if the
3176  * message is later extended, the length should be updated with
3177  * update_openflow_length() before sending.
3178  *
3179  * Returns the header. */
3180 void *
3181 make_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
3182                   struct ofpbuf **bufferp)
3183 {
3184     *bufferp = ofpbuf_new(openflow_len);
3185     return put_openflow_xid(openflow_len, type, xid, *bufferp);
3186 }
3187
3188 /* Similar to make_openflow_xid() but creates a Nicira vendor extension message
3189  * with the specific 'subtype'.  'subtype' should be in host byte order. */
3190 void *
3191 make_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
3192                struct ofpbuf **bufferp)
3193 {
3194     *bufferp = ofpbuf_new(openflow_len);
3195     return put_nxmsg_xid(openflow_len, subtype, xid, *bufferp);
3196 }
3197
3198 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
3199  * with the given 'type' and an arbitrary transaction id.  Allocated bytes
3200  * beyond the header, if any, are zeroed.
3201  *
3202  * The OpenFlow header length is initially set to 'openflow_len'; if the
3203  * message is later extended, the length should be updated with
3204  * update_openflow_length() before sending.
3205  *
3206  * Returns the header. */
3207 void *
3208 put_openflow(size_t openflow_len, uint8_t type, struct ofpbuf *buffer)
3209 {
3210     return put_openflow_xid(openflow_len, type, alloc_xid(), buffer);
3211 }
3212
3213 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
3214  * with the given 'type' and an transaction id 'xid'.  Allocated bytes beyond
3215  * the header, if any, are zeroed.
3216  *
3217  * The OpenFlow header length is initially set to 'openflow_len'; if the
3218  * message is later extended, the length should be updated with
3219  * update_openflow_length() before sending.
3220  *
3221  * Returns the header. */
3222 void *
3223 put_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
3224                  struct ofpbuf *buffer)
3225 {
3226     struct ofp_header *oh;
3227
3228     assert(openflow_len >= sizeof *oh);
3229     assert(openflow_len <= UINT16_MAX);
3230
3231     oh = ofpbuf_put_uninit(buffer, openflow_len);
3232     oh->version = OFP10_VERSION;
3233     oh->type = type;
3234     oh->length = htons(openflow_len);
3235     oh->xid = xid;
3236     memset(oh + 1, 0, openflow_len - sizeof *oh);
3237     return oh;
3238 }
3239
3240 /* Similar to put_openflow() but append a Nicira vendor extension message with
3241  * the specific 'subtype'.  'subtype' should be in host byte order. */
3242 void *
3243 put_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf *buffer)
3244 {
3245     return put_nxmsg_xid(openflow_len, subtype, alloc_xid(), buffer);
3246 }
3247
3248 /* Similar to put_openflow_xid() but append a Nicira vendor extension message
3249  * with the specific 'subtype'.  'subtype' should be in host byte order. */
3250 void *
3251 put_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
3252               struct ofpbuf *buffer)
3253 {
3254     struct nicira_header *nxh;
3255
3256     nxh = put_openflow_xid(openflow_len, OFPT_VENDOR, xid, buffer);
3257     nxh->vendor = htonl(NX_VENDOR_ID);
3258     nxh->subtype = htonl(subtype);
3259     return nxh;
3260 }
3261
3262 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
3263  * 'buffer->size'. */
3264 void
3265 update_openflow_length(struct ofpbuf *buffer)
3266 {
3267     struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
3268     oh->length = htons(buffer->size);
3269 }
3270
3271 static void
3272 put_stats__(ovs_be32 xid, uint8_t ofp_type,
3273             ovs_be16 ofpst_type, ovs_be32 nxst_subtype,
3274             struct ofpbuf *msg)
3275 {
3276     if (ofpst_type == htons(OFPST_VENDOR)) {
3277         struct nicira_stats_msg *nsm;
3278
3279         nsm = put_openflow_xid(sizeof *nsm, ofp_type, xid, msg);
3280         nsm->vsm.osm.type = ofpst_type;
3281         nsm->vsm.vendor = htonl(NX_VENDOR_ID);
3282         nsm->subtype = nxst_subtype;
3283     } else {
3284         struct ofp_stats_msg *osm;
3285
3286         osm = put_openflow_xid(sizeof *osm, ofp_type, xid, msg);
3287         osm->type = ofpst_type;
3288     }
3289 }
3290
3291 /* Creates a statistics request message with total length 'openflow_len'
3292  * (including all headers) and the given 'ofpst_type', and stores the buffer
3293  * containing the new message in '*bufferp'.  If 'ofpst_type' is OFPST_VENDOR
3294  * then 'nxst_subtype' is used as the Nicira vendor extension statistics
3295  * subtype (otherwise 'nxst_subtype' is ignored).
3296  *
3297  * Initializes bytes following the headers to all-bits-zero.
3298  *
3299  * Returns the first byte of the new message. */
3300 void *
3301 ofputil_make_stats_request(size_t openflow_len, uint16_t ofpst_type,
3302                            uint32_t nxst_subtype, struct ofpbuf **bufferp)
3303 {
3304     struct ofpbuf *msg;
3305
3306     msg = *bufferp = ofpbuf_new(openflow_len);
3307     put_stats__(alloc_xid(), OFPT10_STATS_REQUEST,
3308                 htons(ofpst_type), htonl(nxst_subtype), msg);
3309     ofpbuf_padto(msg, openflow_len);
3310
3311     return msg->data;
3312 }
3313
3314 static void
3315 put_stats_reply__(const struct ofp_stats_msg *request, struct ofpbuf *msg)
3316 {
3317     assert(request->header.type == OFPT10_STATS_REQUEST ||
3318            request->header.type == OFPT10_STATS_REPLY);
3319     put_stats__(request->header.xid, OFPT10_STATS_REPLY, request->type,
3320                 (request->type != htons(OFPST_VENDOR)
3321                  ? htonl(0)
3322                  : ((const struct nicira_stats_msg *) request)->subtype),
3323                 msg);
3324 }
3325
3326 /* Creates a statistics reply message with total length 'openflow_len'
3327  * (including all headers) and the same type (either a standard OpenFlow
3328  * statistics type or a Nicira extension type and subtype) as 'request', and
3329  * stores the buffer containing the new message in '*bufferp'.
3330  *
3331  * Initializes bytes following the headers to all-bits-zero.
3332  *
3333  * Returns the first byte of the new message. */
3334 void *
3335 ofputil_make_stats_reply(size_t openflow_len,
3336                          const struct ofp_stats_msg *request,
3337                          struct ofpbuf **bufferp)
3338 {
3339     struct ofpbuf *msg;
3340
3341     msg = *bufferp = ofpbuf_new(openflow_len);
3342     put_stats_reply__(request, msg);
3343     ofpbuf_padto(msg, openflow_len);
3344
3345     return msg->data;
3346 }
3347
3348 /* Initializes 'replies' as a list of ofpbufs that will contain a series of
3349  * replies to 'request', which should be an OpenFlow or Nicira extension
3350  * statistics request.  Initially 'replies' will have a single reply message
3351  * that has only a header.  The functions ofputil_reserve_stats_reply() and
3352  * ofputil_append_stats_reply() may be used to add to the reply. */
3353 void
3354 ofputil_start_stats_reply(const struct ofp_stats_msg *request,
3355                           struct list *replies)
3356 {
3357     struct ofpbuf *msg;
3358
3359     msg = ofpbuf_new(1024);
3360     put_stats_reply__(request, msg);
3361
3362     list_init(replies);
3363     list_push_back(replies, &msg->list_node);
3364 }
3365
3366 /* Prepares to append up to 'len' bytes to the series of statistics replies in
3367  * 'replies', which should have been initialized with
3368  * ofputil_start_stats_reply().  Returns an ofpbuf with at least 'len' bytes of
3369  * tailroom.  (The 'len' bytes have not actually be allocated; the caller must
3370  * do so with e.g. ofpbuf_put_uninit().) */
3371 struct ofpbuf *
3372 ofputil_reserve_stats_reply(size_t len, struct list *replies)
3373 {
3374     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
3375     struct ofp_stats_msg *osm = msg->data;
3376
3377     if (msg->size + len <= UINT16_MAX) {
3378         ofpbuf_prealloc_tailroom(msg, len);
3379     } else {
3380         osm->flags |= htons(OFPSF_REPLY_MORE);
3381
3382         msg = ofpbuf_new(MAX(1024, sizeof(struct nicira_stats_msg) + len));
3383         put_stats_reply__(osm, msg);
3384         list_push_back(replies, &msg->list_node);
3385     }
3386     return msg;
3387 }
3388
3389 /* Appends 'len' bytes to the series of statistics replies in 'replies', and
3390  * returns the first byte. */
3391 void *
3392 ofputil_append_stats_reply(size_t len, struct list *replies)
3393 {
3394     return ofpbuf_put_uninit(ofputil_reserve_stats_reply(len, replies), len);
3395 }
3396
3397 /* Sometimes, when composing stats replies, it's difficult to predict how long
3398  * an individual reply chunk will be before actually encoding it into the reply
3399  * buffer.  This function allows easy handling of this case: just encode the
3400  * reply, then use this function to break the message into two pieces if it
3401  * exceeds the OpenFlow message limit.
3402  *
3403  * In detail, if the final stats message in 'replies' is too long for OpenFlow,
3404  * this function breaks it into two separate stats replies, the first one with
3405  * the first 'start_ofs' bytes, the second one containing the bytes from that
3406  * offset onward. */
3407 void
3408 ofputil_postappend_stats_reply(size_t start_ofs, struct list *replies)
3409 {
3410     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
3411
3412     assert(start_ofs <= UINT16_MAX);
3413     if (msg->size > UINT16_MAX) {
3414         size_t len = msg->size - start_ofs;
3415         memcpy(ofputil_append_stats_reply(len, replies),
3416                (const uint8_t *) msg->data + start_ofs, len);
3417         msg->size = start_ofs;
3418     }
3419 }
3420
3421 /* Returns the first byte past the ofp_stats_msg header in 'oh'. */
3422 const void *
3423 ofputil_stats_body(const struct ofp_header *oh)
3424 {
3425     assert(oh->type == OFPT10_STATS_REQUEST || oh->type == OFPT10_STATS_REPLY);
3426     return (const struct ofp_stats_msg *) oh + 1;
3427 }
3428
3429 /* Returns the number of bytes past the ofp_stats_msg header in 'oh'. */
3430 size_t
3431 ofputil_stats_body_len(const struct ofp_header *oh)
3432 {
3433     assert(oh->type == OFPT10_STATS_REQUEST || oh->type == OFPT10_STATS_REPLY);
3434     return ntohs(oh->length) - sizeof(struct ofp_stats_msg);
3435 }
3436
3437 /* Returns the first byte past the nicira_stats_msg header in 'oh'. */
3438 const void *
3439 ofputil_nxstats_body(const struct ofp_header *oh)
3440 {
3441     assert(oh->type == OFPT10_STATS_REQUEST || oh->type == OFPT10_STATS_REPLY);
3442     return ((const struct nicira_stats_msg *) oh) + 1;
3443 }
3444
3445 /* Returns the number of bytes past the nicira_stats_msg header in 'oh'. */
3446 size_t
3447 ofputil_nxstats_body_len(const struct ofp_header *oh)
3448 {
3449     assert(oh->type == OFPT10_STATS_REQUEST || oh->type == OFPT10_STATS_REPLY);
3450     return ntohs(oh->length) - sizeof(struct nicira_stats_msg);
3451 }
3452
3453 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
3454 struct ofpbuf *
3455 make_echo_request(void)
3456 {
3457     struct ofp_header *rq;
3458     struct ofpbuf *out = ofpbuf_new(sizeof *rq);
3459     rq = ofpbuf_put_uninit(out, sizeof *rq);
3460     rq->version = OFP10_VERSION;
3461     rq->type = OFPT_ECHO_REQUEST;
3462     rq->length = htons(sizeof *rq);
3463     rq->xid = htonl(0);
3464     return out;
3465 }
3466
3467 /* Creates and returns an OFPT_ECHO_REPLY message matching the
3468  * OFPT_ECHO_REQUEST message in 'rq'. */
3469 struct ofpbuf *
3470 make_echo_reply(const struct ofp_header *rq)
3471 {
3472     size_t size = ntohs(rq->length);
3473     struct ofpbuf *out = ofpbuf_new(size);
3474     struct ofp_header *reply = ofpbuf_put(out, rq, size);
3475     reply->type = OFPT_ECHO_REPLY;
3476     return out;
3477 }
3478
3479 struct ofpbuf *
3480 ofputil_encode_barrier_request(void)
3481 {
3482     struct ofpbuf *msg;
3483
3484     make_openflow(sizeof(struct ofp_header), OFPT10_BARRIER_REQUEST, &msg);
3485     return msg;
3486 }
3487
3488 const char *
3489 ofputil_frag_handling_to_string(enum ofp_config_flags flags)
3490 {
3491     switch (flags & OFPC_FRAG_MASK) {
3492     case OFPC_FRAG_NORMAL:   return "normal";
3493     case OFPC_FRAG_DROP:     return "drop";
3494     case OFPC_FRAG_REASM:    return "reassemble";
3495     case OFPC_FRAG_NX_MATCH: return "nx-match";
3496     }
3497
3498     NOT_REACHED();
3499 }
3500
3501 bool
3502 ofputil_frag_handling_from_string(const char *s, enum ofp_config_flags *flags)
3503 {
3504     if (!strcasecmp(s, "normal")) {
3505         *flags = OFPC_FRAG_NORMAL;
3506     } else if (!strcasecmp(s, "drop")) {
3507         *flags = OFPC_FRAG_DROP;
3508     } else if (!strcasecmp(s, "reassemble")) {
3509         *flags = OFPC_FRAG_REASM;
3510     } else if (!strcasecmp(s, "nx-match")) {
3511         *flags = OFPC_FRAG_NX_MATCH;
3512     } else {
3513         return false;
3514     }
3515     return true;
3516 }
3517
3518 /* Converts the OpenFlow 1.1+ port number 'ofp11_port' into an OpenFlow 1.0
3519  * port number and stores the latter in '*ofp10_port', for the purpose of
3520  * decoding OpenFlow 1.1+ protocol messages.  Returns 0 if successful,
3521  * otherwise an OFPERR_* number.
3522  *
3523  * See the definition of OFP11_MAX for an explanation of the mapping. */
3524 enum ofperr
3525 ofputil_port_from_ofp11(ovs_be32 ofp11_port, uint16_t *ofp10_port)
3526 {
3527     uint32_t ofp11_port_h = ntohl(ofp11_port);
3528
3529     if (ofp11_port_h < OFPP_MAX) {
3530         *ofp10_port = ofp11_port_h;
3531         return 0;
3532     } else if (ofp11_port_h >= OFPP11_MAX) {
3533         *ofp10_port = ofp11_port_h - OFPP11_OFFSET;
3534         return 0;
3535     } else {
3536         VLOG_WARN_RL(&bad_ofmsg_rl, "port %"PRIu32" is outside the supported "
3537                      "range 0 through %d or 0x%"PRIx32" through 0x%"PRIx32,
3538                      ofp11_port_h, OFPP_MAX - 1,
3539                      (uint32_t) OFPP11_MAX, UINT32_MAX);
3540         return OFPERR_OFPBAC_BAD_OUT_PORT;
3541     }
3542 }
3543
3544 /* Returns the OpenFlow 1.1+ port number equivalent to the OpenFlow 1.0 port
3545  * number 'ofp10_port', for encoding OpenFlow 1.1+ protocol messages.
3546  *
3547  * See the definition of OFP11_MAX for an explanation of the mapping. */
3548 ovs_be32
3549 ofputil_port_to_ofp11(uint16_t ofp10_port)
3550 {
3551     return htonl(ofp10_port < OFPP_MAX
3552                  ? ofp10_port
3553                  : ofp10_port + OFPP11_OFFSET);
3554 }
3555
3556 /* Checks that 'port' is a valid output port for the OFPAT10_OUTPUT action, given
3557  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
3558  * 'port' is valid, otherwise an OpenFlow return code. */
3559 enum ofperr
3560 ofputil_check_output_port(uint16_t port, int max_ports)
3561 {
3562     switch (port) {
3563     case OFPP_IN_PORT:
3564     case OFPP_TABLE:
3565     case OFPP_NORMAL:
3566     case OFPP_FLOOD:
3567     case OFPP_ALL:
3568     case OFPP_CONTROLLER:
3569     case OFPP_NONE:
3570     case OFPP_LOCAL:
3571         return 0;
3572
3573     default:
3574         if (port < max_ports) {
3575             return 0;
3576         }
3577         return OFPERR_OFPBAC_BAD_OUT_PORT;
3578     }
3579 }
3580
3581 #define OFPUTIL_NAMED_PORTS                     \
3582         OFPUTIL_NAMED_PORT(IN_PORT)             \
3583         OFPUTIL_NAMED_PORT(TABLE)               \
3584         OFPUTIL_NAMED_PORT(NORMAL)              \
3585         OFPUTIL_NAMED_PORT(FLOOD)               \
3586         OFPUTIL_NAMED_PORT(ALL)                 \
3587         OFPUTIL_NAMED_PORT(CONTROLLER)          \
3588         OFPUTIL_NAMED_PORT(LOCAL)               \
3589         OFPUTIL_NAMED_PORT(NONE)
3590
3591 /* Checks whether 's' is the string representation of an OpenFlow port number,
3592  * either as an integer or a string name (e.g. "LOCAL").  If it is, stores the
3593  * number in '*port' and returns true.  Otherwise, returns false. */
3594 bool
3595 ofputil_port_from_string(const char *name, uint16_t *port)
3596 {
3597     struct pair {
3598         const char *name;
3599         uint16_t value;
3600     };
3601     static const struct pair pairs[] = {
3602 #define OFPUTIL_NAMED_PORT(NAME) {#NAME, OFPP_##NAME},
3603         OFPUTIL_NAMED_PORTS
3604 #undef OFPUTIL_NAMED_PORT
3605     };
3606     static const int n_pairs = ARRAY_SIZE(pairs);
3607     int i;
3608
3609     if (str_to_int(name, 0, &i) && i >= 0 && i < UINT16_MAX) {
3610         *port = i;
3611         return true;
3612     }
3613
3614     for (i = 0; i < n_pairs; i++) {
3615         if (!strcasecmp(name, pairs[i].name)) {
3616             *port = pairs[i].value;
3617             return true;
3618         }
3619     }
3620     return false;
3621 }
3622
3623 /* Appends to 's' a string representation of the OpenFlow port number 'port'.
3624  * Most ports' string representation is just the port number, but for special
3625  * ports, e.g. OFPP_LOCAL, it is the name, e.g. "LOCAL". */
3626 void
3627 ofputil_format_port(uint16_t port, struct ds *s)
3628 {
3629     const char *name;
3630
3631     switch (port) {
3632 #define OFPUTIL_NAMED_PORT(NAME) case OFPP_##NAME: name = #NAME; break;
3633         OFPUTIL_NAMED_PORTS
3634 #undef OFPUTIL_NAMED_PORT
3635
3636     default:
3637         ds_put_format(s, "%"PRIu16, port);
3638         return;
3639     }
3640     ds_put_cstr(s, name);
3641 }
3642
3643 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
3644  * 'ofp_version', tries to pull the first element from the array.  If
3645  * successful, initializes '*pp' with an abstract representation of the
3646  * port and returns 0.  If no ports remain to be decoded, returns EOF.
3647  * On an error, returns a positive OFPERR_* value. */
3648 int
3649 ofputil_pull_phy_port(uint8_t ofp_version, struct ofpbuf *b,
3650                       struct ofputil_phy_port *pp)
3651 {
3652     if (ofp_version == OFP10_VERSION) {
3653         const struct ofp10_phy_port *opp = ofpbuf_try_pull(b, sizeof *opp);
3654         return opp ? ofputil_decode_ofp10_phy_port(pp, opp) : EOF;
3655     } else {
3656         const struct ofp11_port *op = ofpbuf_try_pull(b, sizeof *op);
3657         return op ? ofputil_decode_ofp11_port(pp, op) : EOF;
3658     }
3659 }
3660
3661 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
3662  * 'ofp_version', returns the number of elements. */
3663 size_t ofputil_count_phy_ports(uint8_t ofp_version, struct ofpbuf *b)
3664 {
3665     return b->size / ofputil_get_phy_port_size(ofp_version);
3666 }
3667
3668 /* Returns the 'enum ofputil_action_code' corresponding to 'name' (e.g. if
3669  * 'name' is "output" then the return value is OFPUTIL_OFPAT10_OUTPUT), or -1 if
3670  * 'name' is not the name of any action.
3671  *
3672  * ofp-util.def lists the mapping from names to action. */
3673 int
3674 ofputil_action_code_from_name(const char *name)
3675 {
3676     static const char *names[OFPUTIL_N_ACTIONS] = {
3677         NULL,
3678 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)           NAME,
3679 #define OFPAT11_ACTION(ENUM, STRUCT, NAME)           NAME,
3680 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) NAME,
3681 #include "ofp-util.def"
3682     };
3683
3684     const char **p;
3685
3686     for (p = names; p < &names[ARRAY_SIZE(names)]; p++) {
3687         if (*p && !strcasecmp(name, *p)) {
3688             return p - names;
3689         }
3690     }
3691     return -1;
3692 }
3693
3694 /* Appends an action of the type specified by 'code' to 'buf' and returns the
3695  * action.  Initializes the parts of 'action' that identify it as having type
3696  * <ENUM> and length 'sizeof *action' and zeros the rest.  For actions that
3697  * have variable length, the length used and cleared is that of struct
3698  * <STRUCT>.  */
3699 void *
3700 ofputil_put_action(enum ofputil_action_code code, struct ofpbuf *buf)
3701 {
3702     switch (code) {
3703     case OFPUTIL_ACTION_INVALID:
3704         NOT_REACHED();
3705
3706 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                    \
3707     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
3708 #define OFPAT11_ACTION OFPAT10_ACTION
3709 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)        \
3710     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
3711 #include "ofp-util.def"
3712     }
3713     NOT_REACHED();
3714 }
3715
3716 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                        \
3717     void                                                        \
3718     ofputil_init_##ENUM(struct STRUCT *s)                       \
3719     {                                                           \
3720         memset(s, 0, sizeof *s);                                \
3721         s->type = htons(ENUM);                                  \
3722         s->len = htons(sizeof *s);                              \
3723     }                                                           \
3724                                                                 \
3725     struct STRUCT *                                             \
3726     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
3727     {                                                           \
3728         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
3729         ofputil_init_##ENUM(s);                                 \
3730         return s;                                               \
3731     }
3732 #define OFPAT11_ACTION OFPAT10_ACTION
3733 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)            \
3734     void                                                        \
3735     ofputil_init_##ENUM(struct STRUCT *s)                       \
3736     {                                                           \
3737         memset(s, 0, sizeof *s);                                \
3738         s->type = htons(OFPAT10_VENDOR);                        \
3739         s->len = htons(sizeof *s);                              \
3740         s->vendor = htonl(NX_VENDOR_ID);                        \
3741         s->subtype = htons(ENUM);                               \
3742     }                                                           \
3743                                                                 \
3744     struct STRUCT *                                             \
3745     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
3746     {                                                           \
3747         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
3748         ofputil_init_##ENUM(s);                                 \
3749         return s;                                               \
3750     }
3751 #include "ofp-util.def"
3752
3753 /* "Normalizes" the wildcards in 'rule'.  That means:
3754  *
3755  *    1. If the type of level N is known, then only the valid fields for that
3756  *       level may be specified.  For example, ARP does not have a TOS field,
3757  *       so nw_tos must be wildcarded if 'rule' specifies an ARP flow.
3758  *       Similarly, IPv4 does not have any IPv6 addresses, so ipv6_src and
3759  *       ipv6_dst (and other fields) must be wildcarded if 'rule' specifies an
3760  *       IPv4 flow.
3761  *
3762  *    2. If the type of level N is not known (or not understood by Open
3763  *       vSwitch), then no fields at all for that level may be specified.  For
3764  *       example, Open vSwitch does not understand SCTP, an L4 protocol, so the
3765  *       L4 fields tp_src and tp_dst must be wildcarded if 'rule' specifies an
3766  *       SCTP flow.
3767  */
3768 void
3769 ofputil_normalize_rule(struct cls_rule *rule)
3770 {
3771     enum {
3772         MAY_NW_ADDR     = 1 << 0, /* nw_src, nw_dst */
3773         MAY_TP_ADDR     = 1 << 1, /* tp_src, tp_dst */
3774         MAY_NW_PROTO    = 1 << 2, /* nw_proto */
3775         MAY_IPVx        = 1 << 3, /* tos, frag, ttl */
3776         MAY_ARP_SHA     = 1 << 4, /* arp_sha */
3777         MAY_ARP_THA     = 1 << 5, /* arp_tha */
3778         MAY_IPV6        = 1 << 6, /* ipv6_src, ipv6_dst, ipv6_label */
3779         MAY_ND_TARGET   = 1 << 7  /* nd_target */
3780     } may_match;
3781
3782     struct flow_wildcards wc;
3783
3784     /* Figure out what fields may be matched. */
3785     if (rule->flow.dl_type == htons(ETH_TYPE_IP)) {
3786         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_NW_ADDR;
3787         if (rule->flow.nw_proto == IPPROTO_TCP ||
3788             rule->flow.nw_proto == IPPROTO_UDP ||
3789             rule->flow.nw_proto == IPPROTO_ICMP) {
3790             may_match |= MAY_TP_ADDR;
3791         }
3792     } else if (rule->flow.dl_type == htons(ETH_TYPE_IPV6)) {
3793         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_IPV6;
3794         if (rule->flow.nw_proto == IPPROTO_TCP ||
3795             rule->flow.nw_proto == IPPROTO_UDP) {
3796             may_match |= MAY_TP_ADDR;
3797         } else if (rule->flow.nw_proto == IPPROTO_ICMPV6) {
3798             may_match |= MAY_TP_ADDR;
3799             if (rule->flow.tp_src == htons(ND_NEIGHBOR_SOLICIT)) {
3800                 may_match |= MAY_ND_TARGET | MAY_ARP_SHA;
3801             } else if (rule->flow.tp_src == htons(ND_NEIGHBOR_ADVERT)) {
3802                 may_match |= MAY_ND_TARGET | MAY_ARP_THA;
3803             }
3804         }
3805     } else if (rule->flow.dl_type == htons(ETH_TYPE_ARP)) {
3806         may_match = MAY_NW_PROTO | MAY_NW_ADDR | MAY_ARP_SHA | MAY_ARP_THA;
3807     } else {
3808         may_match = 0;
3809     }
3810
3811     /* Clear the fields that may not be matched. */
3812     wc = rule->wc;
3813     if (!(may_match & MAY_NW_ADDR)) {
3814         wc.nw_src_mask = wc.nw_dst_mask = htonl(0);
3815     }
3816     if (!(may_match & MAY_TP_ADDR)) {
3817         wc.tp_src_mask = wc.tp_dst_mask = htons(0);
3818     }
3819     if (!(may_match & MAY_NW_PROTO)) {
3820         wc.wildcards |= FWW_NW_PROTO;
3821     }
3822     if (!(may_match & MAY_IPVx)) {
3823         wc.wildcards |= FWW_NW_DSCP;
3824         wc.wildcards |= FWW_NW_ECN;
3825         wc.wildcards |= FWW_NW_TTL;
3826     }
3827     if (!(may_match & MAY_ARP_SHA)) {
3828         wc.wildcards |= FWW_ARP_SHA;
3829     }
3830     if (!(may_match & MAY_ARP_THA)) {
3831         wc.wildcards |= FWW_ARP_THA;
3832     }
3833     if (!(may_match & MAY_IPV6)) {
3834         wc.ipv6_src_mask = wc.ipv6_dst_mask = in6addr_any;
3835         wc.wildcards |= FWW_IPV6_LABEL;
3836     }
3837     if (!(may_match & MAY_ND_TARGET)) {
3838         wc.nd_target_mask = in6addr_any;
3839     }
3840
3841     /* Log any changes. */
3842     if (!flow_wildcards_equal(&wc, &rule->wc)) {
3843         bool log = !VLOG_DROP_INFO(&bad_ofmsg_rl);
3844         char *pre = log ? cls_rule_to_string(rule) : NULL;
3845
3846         rule->wc = wc;
3847         cls_rule_zero_wildcarded_fields(rule);
3848
3849         if (log) {
3850             char *post = cls_rule_to_string(rule);
3851             VLOG_INFO("normalization changed ofp_match, details:");
3852             VLOG_INFO(" pre: %s", pre);
3853             VLOG_INFO("post: %s", post);
3854             free(pre);
3855             free(post);
3856         }
3857     }
3858 }
3859
3860 /* Parses a key or a key-value pair from '*stringp'.
3861  *
3862  * On success: Stores the key into '*keyp'.  Stores the value, if present, into
3863  * '*valuep', otherwise an empty string.  Advances '*stringp' past the end of
3864  * the key-value pair, preparing it for another call.  '*keyp' and '*valuep'
3865  * are substrings of '*stringp' created by replacing some of its bytes by null
3866  * terminators.  Returns true.
3867  *
3868  * If '*stringp' is just white space or commas, sets '*keyp' and '*valuep' to
3869  * NULL and returns false. */
3870 bool
3871 ofputil_parse_key_value(char **stringp, char **keyp, char **valuep)
3872 {
3873     char *pos, *key, *value;
3874     size_t key_len;
3875
3876     pos = *stringp;
3877     pos += strspn(pos, ", \t\r\n");
3878     if (*pos == '\0') {
3879         *keyp = *valuep = NULL;
3880         return false;
3881     }
3882
3883     key = pos;
3884     key_len = strcspn(pos, ":=(, \t\r\n");
3885     if (key[key_len] == ':' || key[key_len] == '=') {
3886         /* The value can be separated by a colon. */
3887         size_t value_len;
3888
3889         value = key + key_len + 1;
3890         value_len = strcspn(value, ", \t\r\n");
3891         pos = value + value_len + (value[value_len] != '\0');
3892         value[value_len] = '\0';
3893     } else if (key[key_len] == '(') {
3894         /* The value can be surrounded by balanced parentheses.  The outermost
3895          * set of parentheses is removed. */
3896         int level = 1;
3897         size_t value_len;
3898
3899         value = key + key_len + 1;
3900         for (value_len = 0; level > 0; value_len++) {
3901             switch (value[value_len]) {
3902             case '\0':
3903                 level = 0;
3904                 break;
3905
3906             case '(':
3907                 level++;
3908                 break;
3909
3910             case ')':
3911                 level--;
3912                 break;
3913             }
3914         }
3915         value[value_len - 1] = '\0';
3916         pos = value + value_len;
3917     } else {
3918         /* There might be no value at all. */
3919         value = key + key_len;  /* Will become the empty string below. */
3920         pos = key + key_len + (key[key_len] != '\0');
3921     }
3922     key[key_len] = '\0';
3923
3924     *stringp = pos;
3925     *keyp = key;
3926     *valuep = value;
3927     return true;
3928 }