ofp-util: Remove extra blank line.
[sliver-openvswitch.git] / 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-msgs.h"
38 #include "ofp-util.h"
39 #include "ofpbuf.h"
40 #include "packets.h"
41 #include "random.h"
42 #include "unaligned.h"
43 #include "type-props.h"
44 #include "vlog.h"
45
46 VLOG_DEFINE_THIS_MODULE(ofp_util);
47
48 /* Rate limit for OpenFlow message parse errors.  These always indicate a bug
49  * in the peer and so there's not much point in showing a lot of them. */
50 static struct vlog_rate_limit bad_ofmsg_rl = VLOG_RATE_LIMIT_INIT(1, 5);
51
52 /* Given the wildcard bit count in the least-significant 6 of 'wcbits', returns
53  * an IP netmask with a 1 in each bit that must match and a 0 in each bit that
54  * is wildcarded.
55  *
56  * The bits in 'wcbits' are in the format used in enum ofp_flow_wildcards: 0
57  * is exact match, 1 ignores the LSB, 2 ignores the 2 least-significant bits,
58  * ..., 32 and higher wildcard the entire field.  This is the *opposite* of the
59  * usual convention where e.g. /24 indicates that 8 bits (not 24 bits) are
60  * wildcarded. */
61 ovs_be32
62 ofputil_wcbits_to_netmask(int wcbits)
63 {
64     wcbits &= 0x3f;
65     return wcbits < 32 ? htonl(~((1u << wcbits) - 1)) : 0;
66 }
67
68 /* Given the IP netmask 'netmask', returns the number of bits of the IP address
69  * that it wildcards, that is, the number of 0-bits in 'netmask', a number
70  * between 0 and 32 inclusive.
71  *
72  * If 'netmask' is not a CIDR netmask (see ip_is_cidr()), the return value will
73  * still be in the valid range but isn't otherwise meaningful. */
74 int
75 ofputil_netmask_to_wcbits(ovs_be32 netmask)
76 {
77     return 32 - ip_count_cidr_bits(netmask);
78 }
79
80 /* A list of the FWW_* and OFPFW10_ bits that have the same value, meaning, and
81  * name. */
82 #define WC_INVARIANT_LIST \
83     WC_INVARIANT_BIT(IN_PORT) \
84     WC_INVARIANT_BIT(DL_TYPE) \
85     WC_INVARIANT_BIT(NW_PROTO)
86
87 /* Verify that all of the invariant bits (as defined on WC_INVARIANT_LIST)
88  * actually have the same names and values. */
89 #define WC_INVARIANT_BIT(NAME) BUILD_ASSERT_DECL(FWW_##NAME == OFPFW10_##NAME);
90     WC_INVARIANT_LIST
91 #undef WC_INVARIANT_BIT
92
93 /* WC_INVARIANTS is the invariant bits (as defined on WC_INVARIANT_LIST) all
94  * OR'd together. */
95 static const flow_wildcards_t WC_INVARIANTS = 0
96 #define WC_INVARIANT_BIT(NAME) | FWW_##NAME
97     WC_INVARIANT_LIST
98 #undef WC_INVARIANT_BIT
99 ;
100
101 /* Converts the OpenFlow 1.0 wildcards in 'ofpfw' (OFPFW10_*) into a
102  * flow_wildcards in 'wc' for use in struct cls_rule.  It is the caller's
103  * responsibility to handle the special case where the flow match's dl_vlan is
104  * set to OFP_VLAN_NONE. */
105 void
106 ofputil_wildcard_from_ofpfw10(uint32_t ofpfw, struct flow_wildcards *wc)
107 {
108     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 14);
109
110     /* Initialize most of rule->wc. */
111     flow_wildcards_init_catchall(wc);
112     wc->wildcards = (OVS_FORCE flow_wildcards_t) ofpfw & WC_INVARIANTS;
113
114     /* Wildcard fields that aren't defined by ofp10_match. */
115     wc->wildcards |= FWW_NW_ECN | FWW_NW_TTL;
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         ofpfw |= OFPFW10_DL_VLAN_PCP;
238     } else {
239         if (!(rule->wc.vlan_tci_mask & htons(VLAN_VID_MASK))) {
240             ofpfw |= OFPFW10_DL_VLAN;
241         } else {
242             match->dl_vlan = htons(vlan_tci_to_vid(rule->flow.vlan_tci));
243         }
244
245         if (!(rule->wc.vlan_tci_mask & htons(VLAN_PCP_MASK))) {
246             ofpfw |= OFPFW10_DL_VLAN_PCP;
247         } else {
248             match->dl_vlan_pcp = vlan_tci_to_pcp(rule->flow.vlan_tci);
249         }
250     }
251
252     /* Compose most of the match structure. */
253     match->wildcards = htonl(ofpfw);
254     match->in_port = htons(rule->flow.in_port);
255     memcpy(match->dl_src, rule->flow.dl_src, ETH_ADDR_LEN);
256     memcpy(match->dl_dst, rule->flow.dl_dst, ETH_ADDR_LEN);
257     match->dl_type = ofputil_dl_type_to_openflow(rule->flow.dl_type);
258     match->nw_src = rule->flow.nw_src;
259     match->nw_dst = rule->flow.nw_dst;
260     match->nw_tos = rule->flow.nw_tos & IP_DSCP_MASK;
261     match->nw_proto = rule->flow.nw_proto;
262     match->tp_src = rule->flow.tp_src;
263     match->tp_dst = rule->flow.tp_dst;
264     memset(match->pad1, '\0', sizeof match->pad1);
265     memset(match->pad2, '\0', sizeof match->pad2);
266 }
267
268 enum ofperr
269 ofputil_pull_ofp11_match(struct ofpbuf *buf, unsigned int priority,
270                          struct cls_rule *rule)
271 {
272     struct ofp11_match_header *omh;
273     struct ofp11_match *om;
274
275     if (buf->size < sizeof(struct ofp11_match_header)) {
276         return OFPERR_OFPBMC_BAD_LEN;
277     }
278
279     omh = buf->data;
280     switch (ntohs(omh->type)) {
281     case OFPMT_STANDARD:
282         if (omh->length != htons(sizeof *om) || buf->size < sizeof *om) {
283             return OFPERR_OFPBMC_BAD_LEN;
284         }
285         om = ofpbuf_pull(buf, sizeof *om);
286         return ofputil_cls_rule_from_ofp11_match(om, priority, rule);
287
288     default:
289         return OFPERR_OFPBMC_BAD_TYPE;
290     }
291 }
292
293 /* Converts the ofp11_match in 'match' into a cls_rule in 'rule', with the
294  * given 'priority'.  Returns 0 if successful, otherwise an OFPERR_* value. */
295 enum ofperr
296 ofputil_cls_rule_from_ofp11_match(const struct ofp11_match *match,
297                                   unsigned int priority,
298                                   struct cls_rule *rule)
299 {
300     uint16_t wc = ntohl(match->wildcards);
301     uint8_t dl_src_mask[ETH_ADDR_LEN];
302     uint8_t dl_dst_mask[ETH_ADDR_LEN];
303     bool ipv4, arp;
304     int i;
305
306     cls_rule_init_catchall(rule, priority);
307
308     if (!(wc & OFPFW11_IN_PORT)) {
309         uint16_t ofp_port;
310         enum ofperr error;
311
312         error = ofputil_port_from_ofp11(match->in_port, &ofp_port);
313         if (error) {
314             return OFPERR_OFPBMC_BAD_VALUE;
315         }
316         cls_rule_set_in_port(rule, ofp_port);
317     }
318
319     for (i = 0; i < ETH_ADDR_LEN; i++) {
320         dl_src_mask[i] = ~match->dl_src_mask[i];
321     }
322     cls_rule_set_dl_src_masked(rule, match->dl_src, dl_src_mask);
323
324     for (i = 0; i < ETH_ADDR_LEN; i++) {
325         dl_dst_mask[i] = ~match->dl_dst_mask[i];
326     }
327     cls_rule_set_dl_dst_masked(rule, match->dl_dst, dl_dst_mask);
328
329     if (!(wc & OFPFW11_DL_VLAN)) {
330         if (match->dl_vlan == htons(OFPVID11_NONE)) {
331             /* Match only packets without a VLAN tag. */
332             rule->flow.vlan_tci = htons(0);
333             rule->wc.vlan_tci_mask = htons(UINT16_MAX);
334         } else {
335             if (match->dl_vlan == htons(OFPVID11_ANY)) {
336                 /* Match any packet with a VLAN tag regardless of VID. */
337                 rule->flow.vlan_tci = htons(VLAN_CFI);
338                 rule->wc.vlan_tci_mask = htons(VLAN_CFI);
339             } else if (ntohs(match->dl_vlan) < 4096) {
340                 /* Match only packets with the specified VLAN VID. */
341                 rule->flow.vlan_tci = htons(VLAN_CFI) | match->dl_vlan;
342                 rule->wc.vlan_tci_mask = htons(VLAN_CFI | VLAN_VID_MASK);
343             } else {
344                 /* Invalid VID. */
345                 return OFPERR_OFPBMC_BAD_VALUE;
346             }
347
348             if (!(wc & OFPFW11_DL_VLAN_PCP)) {
349                 if (match->dl_vlan_pcp <= 7) {
350                     rule->flow.vlan_tci |= htons(match->dl_vlan_pcp
351                                                  << VLAN_PCP_SHIFT);
352                     rule->wc.vlan_tci_mask |= htons(VLAN_PCP_MASK);
353                 } else {
354                     /* Invalid PCP. */
355                     return OFPERR_OFPBMC_BAD_VALUE;
356                 }
357             }
358         }
359     }
360
361     if (!(wc & OFPFW11_DL_TYPE)) {
362         cls_rule_set_dl_type(rule,
363                              ofputil_dl_type_from_openflow(match->dl_type));
364     }
365
366     ipv4 = rule->flow.dl_type == htons(ETH_TYPE_IP);
367     arp = rule->flow.dl_type == htons(ETH_TYPE_ARP);
368
369     if (ipv4 && !(wc & OFPFW11_NW_TOS)) {
370         if (match->nw_tos & ~IP_DSCP_MASK) {
371             /* Invalid TOS. */
372             return OFPERR_OFPBMC_BAD_VALUE;
373         }
374
375         cls_rule_set_nw_dscp(rule, match->nw_tos);
376     }
377
378     if (ipv4 || arp) {
379         if (!(wc & OFPFW11_NW_PROTO)) {
380             cls_rule_set_nw_proto(rule, match->nw_proto);
381         }
382         cls_rule_set_nw_src_masked(rule, match->nw_src, ~match->nw_src_mask);
383         cls_rule_set_nw_dst_masked(rule, match->nw_dst, ~match->nw_dst_mask);
384     }
385
386 #define OFPFW11_TP_ALL (OFPFW11_TP_SRC | OFPFW11_TP_DST)
387     if (ipv4 && (wc & OFPFW11_TP_ALL) != OFPFW11_TP_ALL) {
388         switch (rule->flow.nw_proto) {
389         case IPPROTO_ICMP:
390             /* "A.2.3 Flow Match Structures" in OF1.1 says:
391              *
392              *    The tp_src and tp_dst fields will be ignored unless the
393              *    network protocol specified is as TCP, UDP or SCTP.
394              *
395              * but I'm pretty sure we should support ICMP too, otherwise
396              * that's a regression from OF1.0. */
397             if (!(wc & OFPFW11_TP_SRC)) {
398                 uint16_t icmp_type = ntohs(match->tp_src);
399                 if (icmp_type < 0x100) {
400                     cls_rule_set_icmp_type(rule, icmp_type);
401                 } else {
402                     return OFPERR_OFPBMC_BAD_FIELD;
403                 }
404             }
405             if (!(wc & OFPFW11_TP_DST)) {
406                 uint16_t icmp_code = ntohs(match->tp_dst);
407                 if (icmp_code < 0x100) {
408                     cls_rule_set_icmp_code(rule, icmp_code);
409                 } else {
410                     return OFPERR_OFPBMC_BAD_FIELD;
411                 }
412             }
413             break;
414
415         case IPPROTO_TCP:
416         case IPPROTO_UDP:
417             if (!(wc & (OFPFW11_TP_SRC))) {
418                 cls_rule_set_tp_src(rule, match->tp_src);
419             }
420             if (!(wc & (OFPFW11_TP_DST))) {
421                 cls_rule_set_tp_dst(rule, match->tp_dst);
422             }
423             break;
424
425         case IPPROTO_SCTP:
426             /* We don't support SCTP and it seems that we should tell the
427              * controller, since OF1.1 implementations are supposed to. */
428             return OFPERR_OFPBMC_BAD_FIELD;
429
430         default:
431             /* OF1.1 says explicitly to ignore this. */
432             break;
433         }
434     }
435
436     if (rule->flow.dl_type == htons(ETH_TYPE_MPLS) ||
437         rule->flow.dl_type == htons(ETH_TYPE_MPLS_MCAST)) {
438         enum { OFPFW11_MPLS_ALL = OFPFW11_MPLS_LABEL | OFPFW11_MPLS_TC };
439
440         if ((wc & OFPFW11_MPLS_ALL) != OFPFW11_MPLS_ALL) {
441             /* MPLS not supported. */
442             return OFPERR_OFPBMC_BAD_TAG;
443         }
444     }
445
446     if (match->metadata_mask != htonll(UINT64_MAX)) {
447         cls_rule_set_metadata_masked(rule, match->metadata,
448                                      ~match->metadata_mask);
449     }
450
451     return 0;
452 }
453
454 /* Convert 'rule' into the OpenFlow 1.1 match structure 'match'. */
455 void
456 ofputil_cls_rule_to_ofp11_match(const struct cls_rule *rule,
457                                 struct ofp11_match *match)
458 {
459     uint32_t wc = 0;
460     int i;
461
462     memset(match, 0, sizeof *match);
463     match->omh.type = htons(OFPMT_STANDARD);
464     match->omh.length = htons(OFPMT11_STANDARD_LENGTH);
465
466     if (rule->wc.wildcards & FWW_IN_PORT) {
467         wc |= OFPFW11_IN_PORT;
468     } else {
469         match->in_port = ofputil_port_to_ofp11(rule->flow.in_port);
470     }
471
472     memcpy(match->dl_src, rule->flow.dl_src, ETH_ADDR_LEN);
473     for (i = 0; i < ETH_ADDR_LEN; i++) {
474         match->dl_src_mask[i] = ~rule->wc.dl_src_mask[i];
475     }
476
477     memcpy(match->dl_dst, rule->flow.dl_dst, ETH_ADDR_LEN);
478     for (i = 0; i < ETH_ADDR_LEN; i++) {
479         match->dl_dst_mask[i] = ~rule->wc.dl_dst_mask[i];
480     }
481
482     if (rule->wc.vlan_tci_mask == htons(0)) {
483         wc |= OFPFW11_DL_VLAN | OFPFW11_DL_VLAN_PCP;
484     } else if (rule->wc.vlan_tci_mask & htons(VLAN_CFI)
485                && !(rule->flow.vlan_tci & htons(VLAN_CFI))) {
486         match->dl_vlan = htons(OFPVID11_NONE);
487         wc |= OFPFW11_DL_VLAN_PCP;
488     } else {
489         if (!(rule->wc.vlan_tci_mask & htons(VLAN_VID_MASK))) {
490             match->dl_vlan = htons(OFPVID11_ANY);
491         } else {
492             match->dl_vlan = htons(vlan_tci_to_vid(rule->flow.vlan_tci));
493         }
494
495         if (!(rule->wc.vlan_tci_mask & htons(VLAN_PCP_MASK))) {
496             wc |= OFPFW11_DL_VLAN_PCP;
497         } else {
498             match->dl_vlan_pcp = vlan_tci_to_pcp(rule->flow.vlan_tci);
499         }
500     }
501
502     if (rule->wc.wildcards & FWW_DL_TYPE) {
503         wc |= OFPFW11_DL_TYPE;
504     } else {
505         match->dl_type = ofputil_dl_type_to_openflow(rule->flow.dl_type);
506     }
507
508     if (rule->wc.wildcards & FWW_NW_DSCP) {
509         wc |= OFPFW11_NW_TOS;
510     } else {
511         match->nw_tos = rule->flow.nw_tos & IP_DSCP_MASK;
512     }
513
514     if (rule->wc.wildcards & FWW_NW_PROTO) {
515         wc |= OFPFW11_NW_PROTO;
516     } else {
517         match->nw_proto = rule->flow.nw_proto;
518     }
519
520     match->nw_src = rule->flow.nw_src;
521     match->nw_src_mask = ~rule->wc.nw_src_mask;
522     match->nw_dst = rule->flow.nw_dst;
523     match->nw_dst_mask = ~rule->wc.nw_dst_mask;
524
525     if (!rule->wc.tp_src_mask) {
526         wc |= OFPFW11_TP_SRC;
527     } else {
528         match->tp_src = rule->flow.tp_src;
529     }
530
531     if (!rule->wc.tp_dst_mask) {
532         wc |= OFPFW11_TP_DST;
533     } else {
534         match->tp_dst = rule->flow.tp_dst;
535     }
536
537     /* MPLS not supported. */
538     wc |= OFPFW11_MPLS_LABEL;
539     wc |= OFPFW11_MPLS_TC;
540
541     match->metadata = rule->flow.metadata;
542     match->metadata_mask = ~rule->wc.metadata_mask;
543
544     match->wildcards = htonl(wc);
545 }
546
547 /* Given a 'dl_type' value in the format used in struct flow, returns the
548  * corresponding 'dl_type' value for use in an ofp10_match or ofp11_match
549  * structure. */
550 ovs_be16
551 ofputil_dl_type_to_openflow(ovs_be16 flow_dl_type)
552 {
553     return (flow_dl_type == htons(FLOW_DL_TYPE_NONE)
554             ? htons(OFP_DL_TYPE_NOT_ETH_TYPE)
555             : flow_dl_type);
556 }
557
558 /* Given a 'dl_type' value in the format used in an ofp10_match or ofp11_match
559  * structure, returns the corresponding 'dl_type' value for use in struct
560  * flow. */
561 ovs_be16
562 ofputil_dl_type_from_openflow(ovs_be16 ofp_dl_type)
563 {
564     return (ofp_dl_type == htons(OFP_DL_TYPE_NOT_ETH_TYPE)
565             ? htons(FLOW_DL_TYPE_NONE)
566             : ofp_dl_type);
567 }
568 \f
569 /* Protocols. */
570
571 struct proto_abbrev {
572     enum ofputil_protocol protocol;
573     const char *name;
574 };
575
576 /* Most users really don't care about some of the differences between
577  * protocols.  These abbreviations help with that. */
578 static const struct proto_abbrev proto_abbrevs[] = {
579     { OFPUTIL_P_ANY,      "any" },
580     { OFPUTIL_P_OF10_ANY, "OpenFlow10" },
581     { OFPUTIL_P_NXM_ANY,  "NXM" },
582 };
583 #define N_PROTO_ABBREVS ARRAY_SIZE(proto_abbrevs)
584
585 enum ofputil_protocol ofputil_flow_dump_protocols[] = {
586     OFPUTIL_P_NXM,
587     OFPUTIL_P_OF10,
588 };
589 size_t ofputil_n_flow_dump_protocols = ARRAY_SIZE(ofputil_flow_dump_protocols);
590
591 /* Returns the ofputil_protocol that is initially in effect on an OpenFlow
592  * connection that has negotiated the given 'version'.  'version' should
593  * normally be an 8-bit OpenFlow version identifier (e.g. 0x01 for OpenFlow
594  * 1.0, 0x02 for OpenFlow 1.1).  Returns 0 if 'version' is not supported or
595  * outside the valid range.  */
596 enum ofputil_protocol
597 ofputil_protocol_from_ofp_version(enum ofp_version version)
598 {
599     switch (version) {
600     case OFP10_VERSION:
601         return OFPUTIL_P_OF10;
602     case OFP12_VERSION:
603         return OFPUTIL_P_OF12;
604     case OFP11_VERSION:
605     default:
606         return 0;
607     }
608 }
609
610 /* Returns the OpenFlow protocol version number (e.g. OFP10_VERSION,
611  * OFP11_VERSION or OFP12_VERSION) that corresponds to 'protocol'. */
612 enum ofp_version
613 ofputil_protocol_to_ofp_version(enum ofputil_protocol protocol)
614 {
615     switch (protocol) {
616     case OFPUTIL_P_OF10:
617     case OFPUTIL_P_OF10_TID:
618     case OFPUTIL_P_NXM:
619     case OFPUTIL_P_NXM_TID:
620         return OFP10_VERSION;
621     case OFPUTIL_P_OF12:
622         return OFP12_VERSION;
623     }
624
625     NOT_REACHED();
626 }
627
628 /* Returns true if 'protocol' is a single OFPUTIL_P_* value, false
629  * otherwise. */
630 bool
631 ofputil_protocol_is_valid(enum ofputil_protocol protocol)
632 {
633     return protocol & OFPUTIL_P_ANY && is_pow2(protocol);
634 }
635
636 /* Returns the equivalent of 'protocol' with the Nicira flow_mod_table_id
637  * extension turned on or off if 'enable' is true or false, respectively.
638  *
639  * This extension is only useful for protocols whose "standard" version does
640  * not allow specific tables to be modified.  In particular, this is true of
641  * OpenFlow 1.0.  In later versions of OpenFlow, a flow_mod request always
642  * specifies a table ID and so there is no need for such an extension.  When
643  * 'protocol' is such a protocol that doesn't need a flow_mod_table_id
644  * extension, this function just returns its 'protocol' argument unchanged
645  * regardless of the value of 'enable'.  */
646 enum ofputil_protocol
647 ofputil_protocol_set_tid(enum ofputil_protocol protocol, bool enable)
648 {
649     switch (protocol) {
650     case OFPUTIL_P_OF10:
651     case OFPUTIL_P_OF10_TID:
652         return enable ? OFPUTIL_P_OF10_TID : OFPUTIL_P_OF10;
653
654     case OFPUTIL_P_NXM:
655     case OFPUTIL_P_NXM_TID:
656         return enable ? OFPUTIL_P_NXM_TID : OFPUTIL_P_NXM;
657
658     case OFPUTIL_P_OF12:
659         return OFPUTIL_P_OF12;
660
661     default:
662         NOT_REACHED();
663     }
664 }
665
666 /* Returns the "base" version of 'protocol'.  That is, if 'protocol' includes
667  * some extension to a standard protocol version, the return value is the
668  * standard version of that protocol without any extension.  If 'protocol' is a
669  * standard protocol version, returns 'protocol' unchanged. */
670 enum ofputil_protocol
671 ofputil_protocol_to_base(enum ofputil_protocol protocol)
672 {
673     return ofputil_protocol_set_tid(protocol, false);
674 }
675
676 /* Returns 'new_base' with any extensions taken from 'cur'. */
677 enum ofputil_protocol
678 ofputil_protocol_set_base(enum ofputil_protocol cur,
679                           enum ofputil_protocol new_base)
680 {
681     bool tid = (cur & OFPUTIL_P_TID) != 0;
682
683     switch (new_base) {
684     case OFPUTIL_P_OF10:
685     case OFPUTIL_P_OF10_TID:
686         return ofputil_protocol_set_tid(OFPUTIL_P_OF10, tid);
687
688     case OFPUTIL_P_NXM:
689     case OFPUTIL_P_NXM_TID:
690         return ofputil_protocol_set_tid(OFPUTIL_P_NXM, tid);
691
692     case OFPUTIL_P_OF12:
693         return ofputil_protocol_set_tid(OFPUTIL_P_OF12, tid);
694
695     default:
696         NOT_REACHED();
697     }
698 }
699
700 /* Returns a string form of 'protocol', if a simple form exists (that is, if
701  * 'protocol' is either a single protocol or it is a combination of protocols
702  * that have a single abbreviation).  Otherwise, returns NULL. */
703 const char *
704 ofputil_protocol_to_string(enum ofputil_protocol protocol)
705 {
706     const struct proto_abbrev *p;
707
708     /* Use a "switch" statement for single-bit names so that we get a compiler
709      * warning if we forget any. */
710     switch (protocol) {
711     case OFPUTIL_P_NXM:
712         return "NXM-table_id";
713
714     case OFPUTIL_P_NXM_TID:
715         return "NXM+table_id";
716
717     case OFPUTIL_P_OF10:
718         return "OpenFlow10-table_id";
719
720     case OFPUTIL_P_OF10_TID:
721         return "OpenFlow10+table_id";
722
723     case OFPUTIL_P_OF12:
724         return NULL;
725     }
726
727     /* Check abbreviations. */
728     for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
729         if (protocol == p->protocol) {
730             return p->name;
731         }
732     }
733
734     return NULL;
735 }
736
737 /* Returns a string that represents 'protocols'.  The return value might be a
738  * comma-separated list if 'protocols' doesn't have a simple name.  The return
739  * value is "none" if 'protocols' is 0.
740  *
741  * The caller must free the returned string (with free()). */
742 char *
743 ofputil_protocols_to_string(enum ofputil_protocol protocols)
744 {
745     struct ds s;
746
747     assert(!(protocols & ~OFPUTIL_P_ANY));
748     if (protocols == 0) {
749         return xstrdup("none");
750     }
751
752     ds_init(&s);
753     while (protocols) {
754         const struct proto_abbrev *p;
755         int i;
756
757         if (s.length) {
758             ds_put_char(&s, ',');
759         }
760
761         for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
762             if ((protocols & p->protocol) == p->protocol) {
763                 ds_put_cstr(&s, p->name);
764                 protocols &= ~p->protocol;
765                 goto match;
766             }
767         }
768
769         for (i = 0; i < CHAR_BIT * sizeof(enum ofputil_protocol); i++) {
770             enum ofputil_protocol bit = 1u << i;
771
772             if (protocols & bit) {
773                 ds_put_cstr(&s, ofputil_protocol_to_string(bit));
774                 protocols &= ~bit;
775                 goto match;
776             }
777         }
778         NOT_REACHED();
779
780     match: ;
781     }
782     return ds_steal_cstr(&s);
783 }
784
785 static enum ofputil_protocol
786 ofputil_protocol_from_string__(const char *s, size_t n)
787 {
788     const struct proto_abbrev *p;
789     int i;
790
791     for (i = 0; i < CHAR_BIT * sizeof(enum ofputil_protocol); i++) {
792         enum ofputil_protocol bit = 1u << i;
793         const char *name = ofputil_protocol_to_string(bit);
794
795         if (name && n == strlen(name) && !strncasecmp(s, name, n)) {
796             return bit;
797         }
798     }
799
800     for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
801         if (n == strlen(p->name) && !strncasecmp(s, p->name, n)) {
802             return p->protocol;
803         }
804     }
805
806     return 0;
807 }
808
809 /* Returns the nonempty set of protocols represented by 's', which can be a
810  * single protocol name or abbreviation or a comma-separated list of them.
811  *
812  * Aborts the program with an error message if 's' is invalid. */
813 enum ofputil_protocol
814 ofputil_protocols_from_string(const char *s)
815 {
816     const char *orig_s = s;
817     enum ofputil_protocol protocols;
818
819     protocols = 0;
820     while (*s) {
821         enum ofputil_protocol p;
822         size_t n;
823
824         n = strcspn(s, ",");
825         if (n == 0) {
826             s++;
827             continue;
828         }
829
830         p = ofputil_protocol_from_string__(s, n);
831         if (!p) {
832             ovs_fatal(0, "%.*s: unknown flow protocol", (int) n, s);
833         }
834         protocols |= p;
835
836         s += n;
837     }
838
839     if (!protocols) {
840         ovs_fatal(0, "%s: no flow protocol specified", orig_s);
841     }
842     return protocols;
843 }
844
845 bool
846 ofputil_packet_in_format_is_valid(enum nx_packet_in_format packet_in_format)
847 {
848     switch (packet_in_format) {
849     case NXPIF_OPENFLOW10:
850     case NXPIF_NXM:
851         return true;
852     }
853
854     return false;
855 }
856
857 const char *
858 ofputil_packet_in_format_to_string(enum nx_packet_in_format packet_in_format)
859 {
860     switch (packet_in_format) {
861     case NXPIF_OPENFLOW10:
862         return "openflow10";
863     case NXPIF_NXM:
864         return "nxm";
865     default:
866         NOT_REACHED();
867     }
868 }
869
870 int
871 ofputil_packet_in_format_from_string(const char *s)
872 {
873     return (!strcmp(s, "openflow10") ? NXPIF_OPENFLOW10
874             : !strcmp(s, "nxm") ? NXPIF_NXM
875             : -1);
876 }
877
878 static bool
879 regs_fully_wildcarded(const struct flow_wildcards *wc)
880 {
881     int i;
882
883     for (i = 0; i < FLOW_N_REGS; i++) {
884         if (wc->reg_masks[i] != 0) {
885             return false;
886         }
887     }
888     return true;
889 }
890
891 /* Returns a bit-mask of ofputil_protocols that can be used for sending 'rule'
892  * to a switch (e.g. to add or remove a flow).  Only NXM can handle tunnel IDs,
893  * registers, or fixing the Ethernet multicast bit.  Otherwise, it's better to
894  * use OpenFlow 1.0 protocol for backward compatibility. */
895 enum ofputil_protocol
896 ofputil_usable_protocols(const struct cls_rule *rule)
897 {
898     const struct flow_wildcards *wc = &rule->wc;
899
900     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 14);
901
902     /* NXM and OF1.1+ supports bitwise matching on ethernet addresses. */
903     if (!eth_mask_is_exact(wc->dl_src_mask)
904         && !eth_addr_is_zero(wc->dl_src_mask)) {
905         return OFPUTIL_P_NXM_ANY;
906     }
907     if (!eth_mask_is_exact(wc->dl_dst_mask)
908         && !eth_addr_is_zero(wc->dl_dst_mask)) {
909         return OFPUTIL_P_NXM_ANY;
910     }
911
912     /* NXM and OF1.1+ support matching metadata. */
913     if (wc->metadata_mask != htonll(0)) {
914         return OFPUTIL_P_NXM_ANY;
915     }
916
917     /* Only NXM supports matching ARP hardware addresses. */
918     if (!eth_addr_is_zero(wc->arp_sha_mask) ||
919         !eth_addr_is_zero(wc->arp_tha_mask)) {
920         return OFPUTIL_P_NXM_ANY;
921     }
922
923     /* Only NXM supports matching IPv6 traffic. */
924     if (!(wc->wildcards & FWW_DL_TYPE)
925             && (rule->flow.dl_type == htons(ETH_TYPE_IPV6))) {
926         return OFPUTIL_P_NXM_ANY;
927     }
928
929     /* Only NXM supports matching registers. */
930     if (!regs_fully_wildcarded(wc)) {
931         return OFPUTIL_P_NXM_ANY;
932     }
933
934     /* Only NXM supports matching tun_id. */
935     if (wc->tun_id_mask != htonll(0)) {
936         return OFPUTIL_P_NXM_ANY;
937     }
938
939     /* Only NXM supports matching fragments. */
940     if (wc->nw_frag_mask) {
941         return OFPUTIL_P_NXM_ANY;
942     }
943
944     /* Only NXM supports matching IPv6 flow label. */
945     if (wc->ipv6_label_mask) {
946         return OFPUTIL_P_NXM_ANY;
947     }
948
949     /* Only NXM supports matching IP ECN bits. */
950     if (!(wc->wildcards & FWW_NW_ECN)) {
951         return OFPUTIL_P_NXM_ANY;
952     }
953
954     /* Only NXM supports matching IP TTL/hop limit. */
955     if (!(wc->wildcards & FWW_NW_TTL)) {
956         return OFPUTIL_P_NXM_ANY;
957     }
958
959     /* Only NXM supports non-CIDR IPv4 address masks. */
960     if (!ip_is_cidr(wc->nw_src_mask) || !ip_is_cidr(wc->nw_dst_mask)) {
961         return OFPUTIL_P_NXM_ANY;
962     }
963
964     /* Only NXM supports bitwise matching on transport port. */
965     if ((wc->tp_src_mask && wc->tp_src_mask != htons(UINT16_MAX)) ||
966         (wc->tp_dst_mask && wc->tp_dst_mask != htons(UINT16_MAX))) {
967         return OFPUTIL_P_NXM_ANY;
968     }
969
970     /* Other formats can express this rule. */
971     return OFPUTIL_P_ANY;
972 }
973
974 /* Returns an OpenFlow message that, sent on an OpenFlow connection whose
975  * protocol is 'current', at least partly transitions the protocol to 'want'.
976  * Stores in '*next' the protocol that will be in effect on the OpenFlow
977  * connection if the switch processes the returned message correctly.  (If
978  * '*next != want' then the caller will have to iterate.)
979  *
980  * If 'current == want', returns NULL and stores 'current' in '*next'. */
981 struct ofpbuf *
982 ofputil_encode_set_protocol(enum ofputil_protocol current,
983                             enum ofputil_protocol want,
984                             enum ofputil_protocol *next)
985 {
986     enum ofputil_protocol cur_base, want_base;
987     bool cur_tid, want_tid;
988
989     cur_base = ofputil_protocol_to_base(current);
990     want_base = ofputil_protocol_to_base(want);
991     if (cur_base != want_base) {
992         *next = ofputil_protocol_set_base(current, want_base);
993
994         switch (want_base) {
995         case OFPUTIL_P_NXM:
996             return ofputil_encode_nx_set_flow_format(NXFF_NXM);
997
998         case OFPUTIL_P_OF10:
999             return ofputil_encode_nx_set_flow_format(NXFF_OPENFLOW10);
1000
1001         case OFPUTIL_P_OF12:
1002             return ofputil_encode_nx_set_flow_format(NXFF_OPENFLOW12);
1003
1004         case OFPUTIL_P_OF10_TID:
1005         case OFPUTIL_P_NXM_TID:
1006             NOT_REACHED();
1007         }
1008     }
1009
1010     cur_tid = (current & OFPUTIL_P_TID) != 0;
1011     want_tid = (want & OFPUTIL_P_TID) != 0;
1012     if (cur_tid != want_tid) {
1013         *next = ofputil_protocol_set_tid(current, want_tid);
1014         return ofputil_make_flow_mod_table_id(want_tid);
1015     }
1016
1017     assert(current == want);
1018
1019     *next = current;
1020     return NULL;
1021 }
1022
1023 /* Returns an NXT_SET_FLOW_FORMAT message that can be used to set the flow
1024  * format to 'nxff'.  */
1025 struct ofpbuf *
1026 ofputil_encode_nx_set_flow_format(enum nx_flow_format nxff)
1027 {
1028     struct nx_set_flow_format *sff;
1029     struct ofpbuf *msg;
1030
1031     assert(ofputil_nx_flow_format_is_valid(nxff));
1032
1033     msg = ofpraw_alloc(OFPRAW_NXT_SET_FLOW_FORMAT, OFP10_VERSION, 0);
1034     sff = ofpbuf_put_zeros(msg, sizeof *sff);
1035     sff->format = htonl(nxff);
1036
1037     return msg;
1038 }
1039
1040 /* Returns the base protocol if 'flow_format' is a valid NXFF_* value, false
1041  * otherwise. */
1042 enum ofputil_protocol
1043 ofputil_nx_flow_format_to_protocol(enum nx_flow_format flow_format)
1044 {
1045     switch (flow_format) {
1046     case NXFF_OPENFLOW10:
1047         return OFPUTIL_P_OF10;
1048
1049     case NXFF_NXM:
1050         return OFPUTIL_P_NXM;
1051
1052     case NXFF_OPENFLOW12:
1053         return OFPUTIL_P_OF12;
1054
1055     default:
1056         return 0;
1057     }
1058 }
1059
1060 /* Returns true if 'flow_format' is a valid NXFF_* value, false otherwise. */
1061 bool
1062 ofputil_nx_flow_format_is_valid(enum nx_flow_format flow_format)
1063 {
1064     return ofputil_nx_flow_format_to_protocol(flow_format) != 0;
1065 }
1066
1067 /* Returns a string version of 'flow_format', which must be a valid NXFF_*
1068  * value. */
1069 const char *
1070 ofputil_nx_flow_format_to_string(enum nx_flow_format flow_format)
1071 {
1072     switch (flow_format) {
1073     case NXFF_OPENFLOW10:
1074         return "openflow10";
1075     case NXFF_NXM:
1076         return "nxm";
1077     case NXFF_OPENFLOW12:
1078         return "openflow12";
1079     default:
1080         NOT_REACHED();
1081     }
1082 }
1083
1084 struct ofpbuf *
1085 ofputil_make_set_packet_in_format(enum nx_packet_in_format packet_in_format)
1086 {
1087     struct nx_set_packet_in_format *spif;
1088     struct ofpbuf *msg;
1089
1090     msg = ofpraw_alloc(OFPRAW_NXT_SET_PACKET_IN_FORMAT, OFP10_VERSION, 0);
1091     spif = ofpbuf_put_zeros(msg, sizeof *spif);
1092     spif->format = htonl(packet_in_format);
1093
1094     return msg;
1095 }
1096
1097 /* Returns an OpenFlow message that can be used to turn the flow_mod_table_id
1098  * extension on or off (according to 'flow_mod_table_id'). */
1099 struct ofpbuf *
1100 ofputil_make_flow_mod_table_id(bool flow_mod_table_id)
1101 {
1102     struct nx_flow_mod_table_id *nfmti;
1103     struct ofpbuf *msg;
1104
1105     msg = ofpraw_alloc(OFPRAW_NXT_FLOW_MOD_TABLE_ID, OFP10_VERSION, 0);
1106     nfmti = ofpbuf_put_zeros(msg, sizeof *nfmti);
1107     nfmti->set = flow_mod_table_id;
1108     return msg;
1109 }
1110
1111 /* Converts an OFPT_FLOW_MOD or NXT_FLOW_MOD message 'oh' into an abstract
1112  * flow_mod in 'fm'.  Returns 0 if successful, otherwise an OpenFlow error
1113  * code.
1114  *
1115  * Uses 'ofpacts' to store the abstract OFPACT_* version of 'oh''s actions.
1116  * The caller must initialize 'ofpacts' and retains ownership of it.
1117  * 'fm->ofpacts' will point into the 'ofpacts' buffer.
1118  *
1119  * Does not validate the flow_mod actions.  The caller should do that, with
1120  * ofpacts_check(). */
1121 enum ofperr
1122 ofputil_decode_flow_mod(struct ofputil_flow_mod *fm,
1123                         const struct ofp_header *oh,
1124                         enum ofputil_protocol protocol,
1125                         struct ofpbuf *ofpacts)
1126 {
1127     uint16_t command;
1128     struct ofpbuf b;
1129     enum ofpraw raw;
1130
1131     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1132     raw = ofpraw_pull_assert(&b);
1133     if (raw == OFPRAW_OFPT11_FLOW_MOD) {
1134         /* Standard OpenFlow 1.1 flow_mod. */
1135         const struct ofp11_flow_mod *ofm;
1136         enum ofperr error;
1137
1138         ofm = ofpbuf_pull(&b, sizeof *ofm);
1139
1140         error = ofputil_pull_ofp11_match(&b, ntohs(ofm->priority), &fm->cr);
1141         if (error) {
1142             return error;
1143         }
1144
1145         error = ofpacts_pull_openflow11_instructions(&b, b.size, ofpacts);
1146         if (error) {
1147             return error;
1148         }
1149
1150         /* Translate the message. */
1151         if (ofm->command == OFPFC_ADD) {
1152             fm->cookie = htonll(0);
1153             fm->cookie_mask = htonll(0);
1154             fm->new_cookie = ofm->cookie;
1155         } else {
1156             /* XXX */
1157             fm->cookie = ofm->cookie;
1158             fm->cookie_mask = ofm->cookie_mask;
1159             fm->new_cookie = htonll(UINT64_MAX);
1160         }
1161         fm->command = ofm->command;
1162         fm->table_id = ofm->table_id;
1163         fm->idle_timeout = ntohs(ofm->idle_timeout);
1164         fm->hard_timeout = ntohs(ofm->hard_timeout);
1165         fm->buffer_id = ntohl(ofm->buffer_id);
1166         error = ofputil_port_from_ofp11(ofm->out_port, &fm->out_port);
1167         if (error) {
1168             return error;
1169         }
1170         if (ofm->out_group != htonl(OFPG_ANY)) {
1171             return OFPERR_NXFMFC_GROUPS_NOT_SUPPORTED;
1172         }
1173         fm->flags = ntohs(ofm->flags);
1174     } else {
1175         if (raw == OFPRAW_OFPT10_FLOW_MOD) {
1176             /* Standard OpenFlow 1.0 flow_mod. */
1177             const struct ofp10_flow_mod *ofm;
1178             uint16_t priority;
1179             enum ofperr error;
1180
1181             /* Get the ofp10_flow_mod. */
1182             ofm = ofpbuf_pull(&b, sizeof *ofm);
1183
1184             /* Set priority based on original wildcards.  Normally we'd allow
1185              * ofputil_cls_rule_from_match() to do this for us, but
1186              * ofputil_normalize_rule() can put wildcards where the original
1187              * flow didn't have them. */
1188             priority = ntohs(ofm->priority);
1189             if (!(ofm->match.wildcards & htonl(OFPFW10_ALL))) {
1190                 priority = UINT16_MAX;
1191             }
1192
1193             /* Translate the rule. */
1194             ofputil_cls_rule_from_ofp10_match(&ofm->match, priority, &fm->cr);
1195             ofputil_normalize_rule(&fm->cr);
1196
1197             /* Now get the actions. */
1198             error = ofpacts_pull_openflow10(&b, b.size, ofpacts);
1199             if (error) {
1200                 return error;
1201             }
1202
1203             /* Translate the message. */
1204             command = ntohs(ofm->command);
1205             fm->cookie = htonll(0);
1206             fm->cookie_mask = htonll(0);
1207             fm->new_cookie = ofm->cookie;
1208             fm->idle_timeout = ntohs(ofm->idle_timeout);
1209             fm->hard_timeout = ntohs(ofm->hard_timeout);
1210             fm->buffer_id = ntohl(ofm->buffer_id);
1211             fm->out_port = ntohs(ofm->out_port);
1212             fm->flags = ntohs(ofm->flags);
1213         } else if (raw == OFPRAW_NXT_FLOW_MOD) {
1214             /* Nicira extended flow_mod. */
1215             const struct nx_flow_mod *nfm;
1216             enum ofperr error;
1217
1218             /* Dissect the message. */
1219             nfm = ofpbuf_pull(&b, sizeof *nfm);
1220             error = nx_pull_match(&b, ntohs(nfm->match_len), ntohs(nfm->priority),
1221                                   &fm->cr, &fm->cookie, &fm->cookie_mask);
1222             if (error) {
1223                 return error;
1224             }
1225             error = ofpacts_pull_openflow10(&b, b.size, ofpacts);
1226             if (error) {
1227                 return error;
1228             }
1229
1230             /* Translate the message. */
1231             command = ntohs(nfm->command);
1232             if ((command & 0xff) == OFPFC_ADD && fm->cookie_mask) {
1233                 /* Flow additions may only set a new cookie, not match an
1234                  * existing cookie. */
1235                 return OFPERR_NXBRC_NXM_INVALID;
1236             }
1237             fm->new_cookie = nfm->cookie;
1238             fm->idle_timeout = ntohs(nfm->idle_timeout);
1239             fm->hard_timeout = ntohs(nfm->hard_timeout);
1240             fm->buffer_id = ntohl(nfm->buffer_id);
1241             fm->out_port = ntohs(nfm->out_port);
1242             fm->flags = ntohs(nfm->flags);
1243         } else {
1244             NOT_REACHED();
1245         }
1246
1247         if (protocol & OFPUTIL_P_TID) {
1248             fm->command = command & 0xff;
1249             fm->table_id = command >> 8;
1250         } else {
1251             fm->command = command;
1252             fm->table_id = 0xff;
1253         }
1254     }
1255
1256     fm->ofpacts = ofpacts->data;
1257     fm->ofpacts_len = ofpacts->size;
1258
1259     return 0;
1260 }
1261
1262 /* Converts 'fm' into an OFPT_FLOW_MOD or NXT_FLOW_MOD message according to
1263  * 'protocol' and returns the message. */
1264 struct ofpbuf *
1265 ofputil_encode_flow_mod(const struct ofputil_flow_mod *fm,
1266                         enum ofputil_protocol protocol)
1267 {
1268     struct ofpbuf *msg;
1269     uint16_t command;
1270
1271     command = (protocol & OFPUTIL_P_TID
1272                ? (fm->command & 0xff) | (fm->table_id << 8)
1273                : fm->command);
1274
1275     switch (protocol) {
1276     case OFPUTIL_P_OF10:
1277     case OFPUTIL_P_OF10_TID: {
1278         struct ofp10_flow_mod *ofm;
1279
1280         msg = ofpraw_alloc(OFPRAW_OFPT10_FLOW_MOD, OFP10_VERSION,
1281                            fm->ofpacts_len);
1282         ofm = ofpbuf_put_zeros(msg, sizeof *ofm);
1283         ofputil_cls_rule_to_ofp10_match(&fm->cr, &ofm->match);
1284         ofm->cookie = fm->new_cookie;
1285         ofm->command = htons(command);
1286         ofm->idle_timeout = htons(fm->idle_timeout);
1287         ofm->hard_timeout = htons(fm->hard_timeout);
1288         ofm->priority = htons(fm->cr.priority);
1289         ofm->buffer_id = htonl(fm->buffer_id);
1290         ofm->out_port = htons(fm->out_port);
1291         ofm->flags = htons(fm->flags);
1292         break;
1293     }
1294
1295     case OFPUTIL_P_NXM:
1296     case OFPUTIL_P_NXM_TID: {
1297         struct nx_flow_mod *nfm;
1298         int match_len;
1299
1300         msg = ofpraw_alloc(OFPRAW_NXT_FLOW_MOD, OFP10_VERSION,
1301                            NXM_TYPICAL_LEN + fm->ofpacts_len);
1302         nfm = ofpbuf_put_zeros(msg, sizeof *nfm);
1303         nfm->command = htons(command);
1304         nfm->cookie = fm->new_cookie;
1305         match_len = nx_put_match(msg, false, &fm->cr,
1306                                  fm->cookie, fm->cookie_mask);
1307         nfm = msg->l3;
1308         nfm->idle_timeout = htons(fm->idle_timeout);
1309         nfm->hard_timeout = htons(fm->hard_timeout);
1310         nfm->priority = htons(fm->cr.priority);
1311         nfm->buffer_id = htonl(fm->buffer_id);
1312         nfm->out_port = htons(fm->out_port);
1313         nfm->flags = htons(fm->flags);
1314         nfm->match_len = htons(match_len);
1315         break;
1316     }
1317
1318     case OFPUTIL_P_OF12:
1319     default:
1320         NOT_REACHED();
1321     }
1322
1323     if (fm->ofpacts) {
1324         ofpacts_put_openflow10(fm->ofpacts, fm->ofpacts_len, msg);
1325     }
1326     ofpmsg_update_length(msg);
1327     return msg;
1328 }
1329
1330 /* Returns a bitmask with a 1-bit for each protocol that could be used to
1331  * send all of the 'n_fm's flow table modification requests in 'fms', and a
1332  * 0-bit for each protocol that is inadequate.
1333  *
1334  * (The return value will have at least one 1-bit.) */
1335 enum ofputil_protocol
1336 ofputil_flow_mod_usable_protocols(const struct ofputil_flow_mod *fms,
1337                                   size_t n_fms)
1338 {
1339     enum ofputil_protocol usable_protocols;
1340     size_t i;
1341
1342     usable_protocols = OFPUTIL_P_ANY;
1343     for (i = 0; i < n_fms; i++) {
1344         const struct ofputil_flow_mod *fm = &fms[i];
1345
1346         usable_protocols &= ofputil_usable_protocols(&fm->cr);
1347         if (fm->table_id != 0xff) {
1348             usable_protocols &= OFPUTIL_P_TID;
1349         }
1350
1351         /* Matching of the cookie is only supported through NXM. */
1352         if (fm->cookie_mask != htonll(0)) {
1353             usable_protocols &= OFPUTIL_P_NXM_ANY;
1354         }
1355     }
1356     assert(usable_protocols);
1357
1358     return usable_protocols;
1359 }
1360
1361 static enum ofperr
1362 ofputil_decode_ofpst_flow_request(struct ofputil_flow_stats_request *fsr,
1363                                   const struct ofp10_flow_stats_request *ofsr,
1364                                   bool aggregate)
1365 {
1366     fsr->aggregate = aggregate;
1367     ofputil_cls_rule_from_ofp10_match(&ofsr->match, 0, &fsr->match);
1368     fsr->out_port = ntohs(ofsr->out_port);
1369     fsr->table_id = ofsr->table_id;
1370     fsr->cookie = fsr->cookie_mask = htonll(0);
1371
1372     return 0;
1373 }
1374
1375 static enum ofperr
1376 ofputil_decode_nxst_flow_request(struct ofputil_flow_stats_request *fsr,
1377                                  struct ofpbuf *b, bool aggregate)
1378 {
1379     const struct nx_flow_stats_request *nfsr;
1380     enum ofperr error;
1381
1382     nfsr = ofpbuf_pull(b, sizeof *nfsr);
1383     error = nx_pull_match(b, ntohs(nfsr->match_len), 0, &fsr->match,
1384                           &fsr->cookie, &fsr->cookie_mask);
1385     if (error) {
1386         return error;
1387     }
1388     if (b->size) {
1389         return OFPERR_OFPBRC_BAD_LEN;
1390     }
1391
1392     fsr->aggregate = aggregate;
1393     fsr->out_port = ntohs(nfsr->out_port);
1394     fsr->table_id = nfsr->table_id;
1395
1396     return 0;
1397 }
1398
1399 /* Converts an OFPST_FLOW, OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE
1400  * request 'oh', into an abstract flow_stats_request in 'fsr'.  Returns 0 if
1401  * successful, otherwise an OpenFlow error code. */
1402 enum ofperr
1403 ofputil_decode_flow_stats_request(struct ofputil_flow_stats_request *fsr,
1404                                   const struct ofp_header *oh)
1405 {
1406     enum ofpraw raw;
1407     struct ofpbuf b;
1408
1409     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1410     raw = ofpraw_pull_assert(&b);
1411     switch ((int) raw) {
1412     case OFPRAW_OFPST_FLOW_REQUEST:
1413         return ofputil_decode_ofpst_flow_request(fsr, b.data, false);
1414
1415     case OFPRAW_OFPST_AGGREGATE_REQUEST:
1416         return ofputil_decode_ofpst_flow_request(fsr, b.data, true);
1417
1418     case OFPRAW_NXST_FLOW_REQUEST:
1419         return ofputil_decode_nxst_flow_request(fsr, &b, false);
1420
1421     case OFPRAW_NXST_AGGREGATE_REQUEST:
1422         return ofputil_decode_nxst_flow_request(fsr, &b, true);
1423
1424     default:
1425         /* Hey, the caller lied. */
1426         NOT_REACHED();
1427     }
1428 }
1429
1430 /* Converts abstract flow_stats_request 'fsr' into an OFPST_FLOW,
1431  * OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE request 'oh' according to
1432  * 'protocol', and returns the message. */
1433 struct ofpbuf *
1434 ofputil_encode_flow_stats_request(const struct ofputil_flow_stats_request *fsr,
1435                                   enum ofputil_protocol protocol)
1436 {
1437     struct ofpbuf *msg;
1438     enum ofpraw raw;
1439
1440     switch (protocol) {
1441     case OFPUTIL_P_OF10:
1442     case OFPUTIL_P_OF10_TID: {
1443         struct ofp10_flow_stats_request *ofsr;
1444
1445         raw = (fsr->aggregate
1446                ? OFPRAW_OFPST_AGGREGATE_REQUEST
1447                : OFPRAW_OFPST_FLOW_REQUEST);
1448         msg = ofpraw_alloc(raw, OFP10_VERSION, 0);
1449         ofsr = ofpbuf_put_zeros(msg, sizeof *ofsr);
1450         ofputil_cls_rule_to_ofp10_match(&fsr->match, &ofsr->match);
1451         ofsr->table_id = fsr->table_id;
1452         ofsr->out_port = htons(fsr->out_port);
1453         break;
1454     }
1455
1456     case OFPUTIL_P_NXM:
1457     case OFPUTIL_P_NXM_TID: {
1458         struct nx_flow_stats_request *nfsr;
1459         int match_len;
1460
1461         raw = (fsr->aggregate
1462                ? OFPRAW_NXST_AGGREGATE_REQUEST
1463                : OFPRAW_NXST_FLOW_REQUEST);
1464         msg = ofpraw_alloc(raw, OFP10_VERSION, 0);
1465         ofpbuf_put_zeros(msg, sizeof *nfsr);
1466         match_len = nx_put_match(msg, false, &fsr->match,
1467                                  fsr->cookie, fsr->cookie_mask);
1468
1469         nfsr = msg->l3;
1470         nfsr->out_port = htons(fsr->out_port);
1471         nfsr->match_len = htons(match_len);
1472         nfsr->table_id = fsr->table_id;
1473         break;
1474     }
1475
1476     case OFPUTIL_P_OF12:
1477     default:
1478         NOT_REACHED();
1479     }
1480
1481     return msg;
1482 }
1483
1484 /* Returns a bitmask with a 1-bit for each protocol that could be used to
1485  * accurately encode 'fsr', and a 0-bit for each protocol that is inadequate.
1486  *
1487  * (The return value will have at least one 1-bit.) */
1488 enum ofputil_protocol
1489 ofputil_flow_stats_request_usable_protocols(
1490     const struct ofputil_flow_stats_request *fsr)
1491 {
1492     enum ofputil_protocol usable_protocols;
1493
1494     usable_protocols = ofputil_usable_protocols(&fsr->match);
1495     if (fsr->cookie_mask != htonll(0)) {
1496         usable_protocols &= OFPUTIL_P_NXM_ANY;
1497     }
1498     return usable_protocols;
1499 }
1500
1501 /* Converts an OFPST_FLOW or NXST_FLOW reply in 'msg' into an abstract
1502  * ofputil_flow_stats in 'fs'.
1503  *
1504  * Multiple OFPST_FLOW or NXST_FLOW replies can be packed into a single
1505  * OpenFlow message.  Calling this function multiple times for a single 'msg'
1506  * iterates through the replies.  The caller must initially leave 'msg''s layer
1507  * pointers null and not modify them between calls.
1508  *
1509  * Most switches don't send the values needed to populate fs->idle_age and
1510  * fs->hard_age, so those members will usually be set to 0.  If the switch from
1511  * which 'msg' originated is known to implement NXT_FLOW_AGE, then pass
1512  * 'flow_age_extension' as true so that the contents of 'msg' determine the
1513  * 'idle_age' and 'hard_age' members in 'fs'.
1514  *
1515  * Uses 'ofpacts' to store the abstract OFPACT_* version of the flow stats
1516  * reply's actions.  The caller must initialize 'ofpacts' and retains ownership
1517  * of it.  'fs->ofpacts' will point into the 'ofpacts' buffer.
1518  *
1519  * Returns 0 if successful, EOF if no replies were left in this 'msg',
1520  * otherwise a positive errno value. */
1521 int
1522 ofputil_decode_flow_stats_reply(struct ofputil_flow_stats *fs,
1523                                 struct ofpbuf *msg,
1524                                 bool flow_age_extension,
1525                                 struct ofpbuf *ofpacts)
1526 {
1527     enum ofperr error;
1528     enum ofpraw raw;
1529
1530     error = (msg->l2
1531              ? ofpraw_decode(&raw, msg->l2)
1532              : ofpraw_pull(&raw, msg));
1533     if (error) {
1534         return error;
1535     }
1536
1537     if (!msg->size) {
1538         return EOF;
1539     } else if (raw == OFPRAW_OFPST_FLOW_REPLY) {
1540         const struct ofp10_flow_stats *ofs;
1541         size_t length;
1542
1543         ofs = ofpbuf_try_pull(msg, sizeof *ofs);
1544         if (!ofs) {
1545             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply has %zu leftover "
1546                          "bytes at end", msg->size);
1547             return EINVAL;
1548         }
1549
1550         length = ntohs(ofs->length);
1551         if (length < sizeof *ofs) {
1552             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply claims invalid "
1553                          "length %zu", length);
1554             return EINVAL;
1555         }
1556
1557         if (ofpacts_pull_openflow10(msg, length - sizeof *ofs, ofpacts)) {
1558             return EINVAL;
1559         }
1560
1561         fs->cookie = get_32aligned_be64(&ofs->cookie);
1562         ofputil_cls_rule_from_ofp10_match(&ofs->match, ntohs(ofs->priority),
1563                                           &fs->rule);
1564         fs->table_id = ofs->table_id;
1565         fs->duration_sec = ntohl(ofs->duration_sec);
1566         fs->duration_nsec = ntohl(ofs->duration_nsec);
1567         fs->idle_timeout = ntohs(ofs->idle_timeout);
1568         fs->hard_timeout = ntohs(ofs->hard_timeout);
1569         fs->idle_age = -1;
1570         fs->hard_age = -1;
1571         fs->packet_count = ntohll(get_32aligned_be64(&ofs->packet_count));
1572         fs->byte_count = ntohll(get_32aligned_be64(&ofs->byte_count));
1573     } else if (raw == OFPRAW_NXST_FLOW_REPLY) {
1574         const struct nx_flow_stats *nfs;
1575         size_t match_len, actions_len, length;
1576
1577         nfs = ofpbuf_try_pull(msg, sizeof *nfs);
1578         if (!nfs) {
1579             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply has %zu leftover "
1580                          "bytes at end", msg->size);
1581             return EINVAL;
1582         }
1583
1584         length = ntohs(nfs->length);
1585         match_len = ntohs(nfs->match_len);
1586         if (length < sizeof *nfs + ROUND_UP(match_len, 8)) {
1587             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply with match_len=%zu "
1588                          "claims invalid length %zu", match_len, length);
1589             return EINVAL;
1590         }
1591         if (nx_pull_match(msg, match_len, ntohs(nfs->priority), &fs->rule,
1592                           NULL, NULL)) {
1593             return EINVAL;
1594         }
1595
1596         actions_len = length - sizeof *nfs - ROUND_UP(match_len, 8);
1597         if (ofpacts_pull_openflow10(msg, actions_len, ofpacts)) {
1598             return EINVAL;
1599         }
1600
1601         fs->cookie = nfs->cookie;
1602         fs->table_id = nfs->table_id;
1603         fs->duration_sec = ntohl(nfs->duration_sec);
1604         fs->duration_nsec = ntohl(nfs->duration_nsec);
1605         fs->idle_timeout = ntohs(nfs->idle_timeout);
1606         fs->hard_timeout = ntohs(nfs->hard_timeout);
1607         fs->idle_age = -1;
1608         fs->hard_age = -1;
1609         if (flow_age_extension) {
1610             if (nfs->idle_age) {
1611                 fs->idle_age = ntohs(nfs->idle_age) - 1;
1612             }
1613             if (nfs->hard_age) {
1614                 fs->hard_age = ntohs(nfs->hard_age) - 1;
1615             }
1616         }
1617         fs->packet_count = ntohll(nfs->packet_count);
1618         fs->byte_count = ntohll(nfs->byte_count);
1619     } else {
1620         NOT_REACHED();
1621     }
1622
1623     fs->ofpacts = ofpacts->data;
1624     fs->ofpacts_len = ofpacts->size;
1625
1626     return 0;
1627 }
1628
1629 /* Returns 'count' unchanged except that UINT64_MAX becomes 0.
1630  *
1631  * We use this in situations where OVS internally uses UINT64_MAX to mean
1632  * "value unknown" but OpenFlow 1.0 does not define any unknown value. */
1633 static uint64_t
1634 unknown_to_zero(uint64_t count)
1635 {
1636     return count != UINT64_MAX ? count : 0;
1637 }
1638
1639 /* Appends an OFPST_FLOW or NXST_FLOW reply that contains the data in 'fs' to
1640  * those already present in the list of ofpbufs in 'replies'.  'replies' should
1641  * have been initialized with ofputil_start_stats_reply(). */
1642 void
1643 ofputil_append_flow_stats_reply(const struct ofputil_flow_stats *fs,
1644                                 struct list *replies)
1645 {
1646     struct ofpbuf *reply = ofpbuf_from_list(list_back(replies));
1647     size_t start_ofs = reply->size;
1648     enum ofpraw raw;
1649
1650     ofpraw_decode_partial(&raw, reply->data, reply->size);
1651     if (raw == OFPRAW_OFPST_FLOW_REPLY) {
1652         struct ofp10_flow_stats *ofs;
1653
1654         ofpbuf_put_uninit(reply, sizeof *ofs);
1655         ofpacts_put_openflow10(fs->ofpacts, fs->ofpacts_len, reply);
1656
1657         ofs = ofpbuf_at_assert(reply, start_ofs, sizeof *ofs);
1658         ofs->length = htons(reply->size - start_ofs);
1659         ofs->table_id = fs->table_id;
1660         ofs->pad = 0;
1661         ofputil_cls_rule_to_ofp10_match(&fs->rule, &ofs->match);
1662         ofs->duration_sec = htonl(fs->duration_sec);
1663         ofs->duration_nsec = htonl(fs->duration_nsec);
1664         ofs->priority = htons(fs->rule.priority);
1665         ofs->idle_timeout = htons(fs->idle_timeout);
1666         ofs->hard_timeout = htons(fs->hard_timeout);
1667         memset(ofs->pad2, 0, sizeof ofs->pad2);
1668         put_32aligned_be64(&ofs->cookie, fs->cookie);
1669         put_32aligned_be64(&ofs->packet_count,
1670                            htonll(unknown_to_zero(fs->packet_count)));
1671         put_32aligned_be64(&ofs->byte_count,
1672                            htonll(unknown_to_zero(fs->byte_count)));
1673     } else if (raw == OFPRAW_NXST_FLOW_REPLY) {
1674         struct nx_flow_stats *nfs;
1675         int match_len;
1676
1677         ofpbuf_put_uninit(reply, sizeof *nfs);
1678         match_len = nx_put_match(reply, false, &fs->rule, 0, 0);
1679         ofpacts_put_openflow10(fs->ofpacts, fs->ofpacts_len, reply);
1680
1681         nfs = ofpbuf_at_assert(reply, start_ofs, sizeof *nfs);
1682         nfs->length = htons(reply->size - start_ofs);
1683         nfs->table_id = fs->table_id;
1684         nfs->pad = 0;
1685         nfs->duration_sec = htonl(fs->duration_sec);
1686         nfs->duration_nsec = htonl(fs->duration_nsec);
1687         nfs->priority = htons(fs->rule.priority);
1688         nfs->idle_timeout = htons(fs->idle_timeout);
1689         nfs->hard_timeout = htons(fs->hard_timeout);
1690         nfs->idle_age = htons(fs->idle_age < 0 ? 0
1691                               : fs->idle_age < UINT16_MAX ? fs->idle_age + 1
1692                               : UINT16_MAX);
1693         nfs->hard_age = htons(fs->hard_age < 0 ? 0
1694                               : fs->hard_age < UINT16_MAX ? fs->hard_age + 1
1695                               : UINT16_MAX);
1696         nfs->match_len = htons(match_len);
1697         nfs->cookie = fs->cookie;
1698         nfs->packet_count = htonll(fs->packet_count);
1699         nfs->byte_count = htonll(fs->byte_count);
1700     } else {
1701         NOT_REACHED();
1702     }
1703
1704     ofpmp_postappend(replies, start_ofs);
1705 }
1706
1707 /* Converts abstract ofputil_aggregate_stats 'stats' into an OFPST_AGGREGATE or
1708  * NXST_AGGREGATE reply matching 'request', and returns the message. */
1709 struct ofpbuf *
1710 ofputil_encode_aggregate_stats_reply(
1711     const struct ofputil_aggregate_stats *stats,
1712     const struct ofp_header *request)
1713 {
1714     struct ofp_aggregate_stats_reply *asr;
1715     uint64_t packet_count;
1716     uint64_t byte_count;
1717     struct ofpbuf *msg;
1718     enum ofpraw raw;
1719
1720     ofpraw_decode(&raw, request);
1721     if (raw == OFPRAW_OFPST_AGGREGATE_REQUEST) {
1722         packet_count = unknown_to_zero(stats->packet_count);
1723         byte_count = unknown_to_zero(stats->byte_count);
1724     } else {
1725         packet_count = stats->packet_count;
1726         byte_count = stats->byte_count;
1727     }
1728
1729     msg = ofpraw_alloc_stats_reply(request, 0);
1730     asr = ofpbuf_put_zeros(msg, sizeof *asr);
1731     put_32aligned_be64(&asr->packet_count, htonll(packet_count));
1732     put_32aligned_be64(&asr->byte_count, htonll(byte_count));
1733     asr->flow_count = htonl(stats->flow_count);
1734
1735     return msg;
1736 }
1737
1738 enum ofperr
1739 ofputil_decode_aggregate_stats_reply(struct ofputil_aggregate_stats *stats,
1740                                      const struct ofp_header *reply)
1741 {
1742     struct ofp_aggregate_stats_reply *asr;
1743     struct ofpbuf msg;
1744
1745     ofpbuf_use_const(&msg, reply, ntohs(reply->length));
1746     ofpraw_pull_assert(&msg);
1747
1748     asr = msg.l3;
1749     stats->packet_count = ntohll(get_32aligned_be64(&asr->packet_count));
1750     stats->byte_count = ntohll(get_32aligned_be64(&asr->byte_count));
1751     stats->flow_count = ntohl(asr->flow_count);
1752
1753     return 0;
1754 }
1755
1756 /* Converts an OFPT_FLOW_REMOVED or NXT_FLOW_REMOVED message 'oh' into an
1757  * abstract ofputil_flow_removed in 'fr'.  Returns 0 if successful, otherwise
1758  * an OpenFlow error code. */
1759 enum ofperr
1760 ofputil_decode_flow_removed(struct ofputil_flow_removed *fr,
1761                             const struct ofp_header *oh)
1762 {
1763     enum ofpraw raw;
1764     struct ofpbuf b;
1765
1766     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1767     raw = ofpraw_pull_assert(&b);
1768     if (raw == OFPRAW_OFPT10_FLOW_REMOVED) {
1769         const struct ofp_flow_removed *ofr;
1770
1771         ofr = ofpbuf_pull(&b, sizeof *ofr);
1772
1773         ofputil_cls_rule_from_ofp10_match(&ofr->match, ntohs(ofr->priority),
1774                                           &fr->rule);
1775         fr->cookie = ofr->cookie;
1776         fr->reason = ofr->reason;
1777         fr->duration_sec = ntohl(ofr->duration_sec);
1778         fr->duration_nsec = ntohl(ofr->duration_nsec);
1779         fr->idle_timeout = ntohs(ofr->idle_timeout);
1780         fr->packet_count = ntohll(ofr->packet_count);
1781         fr->byte_count = ntohll(ofr->byte_count);
1782     } else if (raw == OFPRAW_NXT_FLOW_REMOVED) {
1783         struct nx_flow_removed *nfr;
1784         int error;
1785
1786         nfr = ofpbuf_pull(&b, sizeof *nfr);
1787         error = nx_pull_match(&b, ntohs(nfr->match_len), ntohs(nfr->priority),
1788                               &fr->rule, NULL, NULL);
1789         if (error) {
1790             return error;
1791         }
1792         if (b.size) {
1793             return OFPERR_OFPBRC_BAD_LEN;
1794         }
1795
1796         fr->cookie = nfr->cookie;
1797         fr->reason = nfr->reason;
1798         fr->duration_sec = ntohl(nfr->duration_sec);
1799         fr->duration_nsec = ntohl(nfr->duration_nsec);
1800         fr->idle_timeout = ntohs(nfr->idle_timeout);
1801         fr->packet_count = ntohll(nfr->packet_count);
1802         fr->byte_count = ntohll(nfr->byte_count);
1803     } else {
1804         NOT_REACHED();
1805     }
1806
1807     return 0;
1808 }
1809
1810 /* Converts abstract ofputil_flow_removed 'fr' into an OFPT_FLOW_REMOVED or
1811  * NXT_FLOW_REMOVED message 'oh' according to 'protocol', and returns the
1812  * message. */
1813 struct ofpbuf *
1814 ofputil_encode_flow_removed(const struct ofputil_flow_removed *fr,
1815                             enum ofputil_protocol protocol)
1816 {
1817     struct ofpbuf *msg;
1818
1819     switch (protocol) {
1820     case OFPUTIL_P_OF10:
1821     case OFPUTIL_P_OF10_TID: {
1822         struct ofp_flow_removed *ofr;
1823
1824         msg = ofpraw_alloc_xid(OFPRAW_OFPT10_FLOW_REMOVED, OFP10_VERSION,
1825                                htonl(0), 0);
1826         ofr = ofpbuf_put_zeros(msg, sizeof *ofr);
1827         ofputil_cls_rule_to_ofp10_match(&fr->rule, &ofr->match);
1828         ofr->cookie = fr->cookie;
1829         ofr->priority = htons(fr->rule.priority);
1830         ofr->reason = fr->reason;
1831         ofr->duration_sec = htonl(fr->duration_sec);
1832         ofr->duration_nsec = htonl(fr->duration_nsec);
1833         ofr->idle_timeout = htons(fr->idle_timeout);
1834         ofr->packet_count = htonll(unknown_to_zero(fr->packet_count));
1835         ofr->byte_count = htonll(unknown_to_zero(fr->byte_count));
1836         break;
1837     }
1838
1839     case OFPUTIL_P_NXM:
1840     case OFPUTIL_P_NXM_TID: {
1841         struct nx_flow_removed *nfr;
1842         int match_len;
1843
1844         msg = ofpraw_alloc_xid(OFPRAW_NXT_FLOW_REMOVED, OFP10_VERSION,
1845                                htonl(0), NXM_TYPICAL_LEN);
1846         nfr = ofpbuf_put_zeros(msg, sizeof *nfr);
1847         match_len = nx_put_match(msg, false, &fr->rule, 0, 0);
1848
1849         nfr = msg->l3;
1850         nfr->cookie = fr->cookie;
1851         nfr->priority = htons(fr->rule.priority);
1852         nfr->reason = fr->reason;
1853         nfr->duration_sec = htonl(fr->duration_sec);
1854         nfr->duration_nsec = htonl(fr->duration_nsec);
1855         nfr->idle_timeout = htons(fr->idle_timeout);
1856         nfr->match_len = htons(match_len);
1857         nfr->packet_count = htonll(fr->packet_count);
1858         nfr->byte_count = htonll(fr->byte_count);
1859         break;
1860     }
1861
1862     case OFPUTIL_P_OF12:
1863     default:
1864         NOT_REACHED();
1865     }
1866
1867     return msg;
1868 }
1869
1870 enum ofperr
1871 ofputil_decode_packet_in(struct ofputil_packet_in *pin,
1872                          const struct ofp_header *oh)
1873 {
1874     enum ofpraw raw;
1875     struct ofpbuf b;
1876
1877     memset(pin, 0, sizeof *pin);
1878
1879     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1880     raw = ofpraw_pull_assert(&b);
1881     if (raw == OFPRAW_OFPT10_PACKET_IN) {
1882         const struct ofp_packet_in *opi;
1883
1884         opi = ofpbuf_pull(&b, offsetof(struct ofp_packet_in, data));
1885
1886         pin->packet = opi->data;
1887         pin->packet_len = b.size;
1888
1889         pin->fmd.in_port = ntohs(opi->in_port);
1890         pin->reason = opi->reason;
1891         pin->buffer_id = ntohl(opi->buffer_id);
1892         pin->total_len = ntohs(opi->total_len);
1893     } else if (raw == OFPRAW_NXT_PACKET_IN) {
1894         const struct nx_packet_in *npi;
1895         struct cls_rule rule;
1896         int error;
1897
1898         npi = ofpbuf_pull(&b, sizeof *npi);
1899         error = nx_pull_match_loose(&b, ntohs(npi->match_len), 0, &rule, NULL,
1900                                     NULL);
1901         if (error) {
1902             return error;
1903         }
1904
1905         if (!ofpbuf_try_pull(&b, 2)) {
1906             return OFPERR_OFPBRC_BAD_LEN;
1907         }
1908
1909         pin->packet = b.data;
1910         pin->packet_len = b.size;
1911         pin->reason = npi->reason;
1912         pin->table_id = npi->table_id;
1913         pin->cookie = npi->cookie;
1914
1915         pin->fmd.in_port = rule.flow.in_port;
1916
1917         pin->fmd.tun_id = rule.flow.tun_id;
1918         pin->fmd.tun_id_mask = rule.wc.tun_id_mask;
1919
1920         pin->fmd.metadata = rule.flow.metadata;
1921         pin->fmd.metadata_mask = rule.wc.metadata_mask;
1922
1923         memcpy(pin->fmd.regs, rule.flow.regs, sizeof pin->fmd.regs);
1924         memcpy(pin->fmd.reg_masks, rule.wc.reg_masks,
1925                sizeof pin->fmd.reg_masks);
1926
1927         pin->buffer_id = ntohl(npi->buffer_id);
1928         pin->total_len = ntohs(npi->total_len);
1929     } else {
1930         NOT_REACHED();
1931     }
1932
1933     return 0;
1934 }
1935
1936 /* Converts abstract ofputil_packet_in 'pin' into a PACKET_IN message
1937  * in the format specified by 'packet_in_format'.  */
1938 struct ofpbuf *
1939 ofputil_encode_packet_in(const struct ofputil_packet_in *pin,
1940                          enum nx_packet_in_format packet_in_format)
1941 {
1942     size_t send_len = MIN(pin->send_len, pin->packet_len);
1943     struct ofpbuf *packet;
1944
1945     /* Add OFPT_PACKET_IN. */
1946     if (packet_in_format == NXPIF_OPENFLOW10) {
1947         struct ofp_packet_in *opi;
1948
1949         packet = ofpraw_alloc_xid(OFPRAW_OFPT10_PACKET_IN, OFP10_VERSION,
1950                                   htonl(0), send_len);
1951         opi = ofpbuf_put_zeros(packet, offsetof(struct ofp_packet_in, data));
1952         opi->total_len = htons(pin->total_len);
1953         opi->in_port = htons(pin->fmd.in_port);
1954         opi->reason = pin->reason;
1955         opi->buffer_id = htonl(pin->buffer_id);
1956
1957         ofpbuf_put(packet, pin->packet, send_len);
1958     } else if (packet_in_format == NXPIF_NXM) {
1959         struct nx_packet_in *npi;
1960         struct cls_rule rule;
1961         size_t match_len;
1962         size_t i;
1963
1964         cls_rule_init_catchall(&rule, 0);
1965         cls_rule_set_tun_id_masked(&rule, pin->fmd.tun_id,
1966                                    pin->fmd.tun_id_mask);
1967         cls_rule_set_metadata_masked(&rule, pin->fmd.metadata,
1968                                    pin->fmd.metadata_mask);
1969
1970
1971         for (i = 0; i < FLOW_N_REGS; i++) {
1972             cls_rule_set_reg_masked(&rule, i, pin->fmd.regs[i],
1973                                     pin->fmd.reg_masks[i]);
1974         }
1975
1976         cls_rule_set_in_port(&rule, pin->fmd.in_port);
1977
1978         /* The final argument is just an estimate of the space required. */
1979         packet = ofpraw_alloc_xid(OFPRAW_NXT_PACKET_IN, OFP10_VERSION,
1980                                   htonl(0), (sizeof(struct flow_metadata) * 2
1981                                              + 2 + send_len));
1982         ofpbuf_put_zeros(packet, sizeof *npi);
1983         match_len = nx_put_match(packet, false, &rule, 0, 0);
1984         ofpbuf_put_zeros(packet, 2);
1985         ofpbuf_put(packet, pin->packet, send_len);
1986
1987         npi = packet->l3;
1988         npi->buffer_id = htonl(pin->buffer_id);
1989         npi->total_len = htons(pin->total_len);
1990         npi->reason = pin->reason;
1991         npi->table_id = pin->table_id;
1992         npi->cookie = pin->cookie;
1993         npi->match_len = htons(match_len);
1994     } else {
1995         NOT_REACHED();
1996     }
1997     ofpmsg_update_length(packet);
1998
1999     return packet;
2000 }
2001
2002 const char *
2003 ofputil_packet_in_reason_to_string(enum ofp_packet_in_reason reason)
2004 {
2005     static char s[INT_STRLEN(int) + 1];
2006
2007     switch (reason) {
2008     case OFPR_NO_MATCH:
2009         return "no_match";
2010     case OFPR_ACTION:
2011         return "action";
2012     case OFPR_INVALID_TTL:
2013         return "invalid_ttl";
2014
2015     case OFPR_N_REASONS:
2016     default:
2017         sprintf(s, "%d", (int) reason);
2018         return s;
2019     }
2020 }
2021
2022 bool
2023 ofputil_packet_in_reason_from_string(const char *s,
2024                                      enum ofp_packet_in_reason *reason)
2025 {
2026     int i;
2027
2028     for (i = 0; i < OFPR_N_REASONS; i++) {
2029         if (!strcasecmp(s, ofputil_packet_in_reason_to_string(i))) {
2030             *reason = i;
2031             return true;
2032         }
2033     }
2034     return false;
2035 }
2036
2037 /* Converts an OFPT_PACKET_OUT in 'opo' into an abstract ofputil_packet_out in
2038  * 'po'.
2039  *
2040  * Uses 'ofpacts' to store the abstract OFPACT_* version of the packet out
2041  * message's actions.  The caller must initialize 'ofpacts' and retains
2042  * ownership of it.  'po->ofpacts' will point into the 'ofpacts' buffer.
2043  *
2044  * Returns 0 if successful, otherwise an OFPERR_* value. */
2045 enum ofperr
2046 ofputil_decode_packet_out(struct ofputil_packet_out *po,
2047                           const struct ofp_header *oh,
2048                           struct ofpbuf *ofpacts)
2049 {
2050     const struct ofp_packet_out *opo;
2051     enum ofperr error;
2052     enum ofpraw raw;
2053     struct ofpbuf b;
2054
2055     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2056     raw = ofpraw_pull_assert(&b);
2057     assert(raw == OFPRAW_OFPT10_PACKET_OUT);
2058
2059     opo = ofpbuf_pull(&b, sizeof *opo);
2060     po->buffer_id = ntohl(opo->buffer_id);
2061     po->in_port = ntohs(opo->in_port);
2062     if (po->in_port >= OFPP_MAX && po->in_port != OFPP_LOCAL
2063         && po->in_port != OFPP_NONE && po->in_port != OFPP_CONTROLLER) {
2064         VLOG_WARN_RL(&bad_ofmsg_rl, "packet-out has bad input port %#"PRIx16,
2065                      po->in_port);
2066         return OFPERR_NXBRC_BAD_IN_PORT;
2067     }
2068
2069     error = ofpacts_pull_openflow10(&b, ntohs(opo->actions_len), ofpacts);
2070     if (error) {
2071         return error;
2072     }
2073     po->ofpacts = ofpacts->data;
2074     po->ofpacts_len = ofpacts->size;
2075
2076     if (po->buffer_id == UINT32_MAX) {
2077         po->packet = b.data;
2078         po->packet_len = b.size;
2079     } else {
2080         po->packet = NULL;
2081         po->packet_len = 0;
2082     }
2083
2084     return 0;
2085 }
2086 \f
2087 /* ofputil_phy_port */
2088
2089 /* NETDEV_F_* to and from OFPPF_* and OFPPF10_*. */
2090 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_HD    == OFPPF_10MB_HD);  /* bit 0 */
2091 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_FD    == OFPPF_10MB_FD);  /* bit 1 */
2092 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_HD   == OFPPF_100MB_HD); /* bit 2 */
2093 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_FD   == OFPPF_100MB_FD); /* bit 3 */
2094 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_HD     == OFPPF_1GB_HD);   /* bit 4 */
2095 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_FD     == OFPPF_1GB_FD);   /* bit 5 */
2096 BUILD_ASSERT_DECL((int) NETDEV_F_10GB_FD    == OFPPF_10GB_FD);  /* bit 6 */
2097
2098 /* NETDEV_F_ bits 11...15 are OFPPF10_ bits 7...11: */
2099 BUILD_ASSERT_DECL((int) NETDEV_F_COPPER == (OFPPF10_COPPER << 4));
2100 BUILD_ASSERT_DECL((int) NETDEV_F_FIBER == (OFPPF10_FIBER << 4));
2101 BUILD_ASSERT_DECL((int) NETDEV_F_AUTONEG == (OFPPF10_AUTONEG << 4));
2102 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE == (OFPPF10_PAUSE << 4));
2103 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE_ASYM == (OFPPF10_PAUSE_ASYM << 4));
2104
2105 static enum netdev_features
2106 netdev_port_features_from_ofp10(ovs_be32 ofp10_)
2107 {
2108     uint32_t ofp10 = ntohl(ofp10_);
2109     return (ofp10 & 0x7f) | ((ofp10 & 0xf80) << 4);
2110 }
2111
2112 static ovs_be32
2113 netdev_port_features_to_ofp10(enum netdev_features features)
2114 {
2115     return htonl((features & 0x7f) | ((features & 0xf800) >> 4));
2116 }
2117
2118 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_HD    == OFPPF_10MB_HD);     /* bit 0 */
2119 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_FD    == OFPPF_10MB_FD);     /* bit 1 */
2120 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_HD   == OFPPF_100MB_HD);    /* bit 2 */
2121 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_FD   == OFPPF_100MB_FD);    /* bit 3 */
2122 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_HD     == OFPPF_1GB_HD);      /* bit 4 */
2123 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_FD     == OFPPF_1GB_FD);      /* bit 5 */
2124 BUILD_ASSERT_DECL((int) NETDEV_F_10GB_FD    == OFPPF_10GB_FD);     /* bit 6 */
2125 BUILD_ASSERT_DECL((int) NETDEV_F_40GB_FD    == OFPPF11_40GB_FD);   /* bit 7 */
2126 BUILD_ASSERT_DECL((int) NETDEV_F_100GB_FD   == OFPPF11_100GB_FD);  /* bit 8 */
2127 BUILD_ASSERT_DECL((int) NETDEV_F_1TB_FD     == OFPPF11_1TB_FD);    /* bit 9 */
2128 BUILD_ASSERT_DECL((int) NETDEV_F_OTHER      == OFPPF11_OTHER);     /* bit 10 */
2129 BUILD_ASSERT_DECL((int) NETDEV_F_COPPER     == OFPPF11_COPPER);    /* bit 11 */
2130 BUILD_ASSERT_DECL((int) NETDEV_F_FIBER      == OFPPF11_FIBER);     /* bit 12 */
2131 BUILD_ASSERT_DECL((int) NETDEV_F_AUTONEG    == OFPPF11_AUTONEG);   /* bit 13 */
2132 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE      == OFPPF11_PAUSE);     /* bit 14 */
2133 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE_ASYM == OFPPF11_PAUSE_ASYM);/* bit 15 */
2134
2135 static enum netdev_features
2136 netdev_port_features_from_ofp11(ovs_be32 ofp11)
2137 {
2138     return ntohl(ofp11) & 0xffff;
2139 }
2140
2141 static ovs_be32
2142 netdev_port_features_to_ofp11(enum netdev_features features)
2143 {
2144     return htonl(features & 0xffff);
2145 }
2146
2147 static enum ofperr
2148 ofputil_decode_ofp10_phy_port(struct ofputil_phy_port *pp,
2149                               const struct ofp10_phy_port *opp)
2150 {
2151     memset(pp, 0, sizeof *pp);
2152
2153     pp->port_no = ntohs(opp->port_no);
2154     memcpy(pp->hw_addr, opp->hw_addr, OFP_ETH_ALEN);
2155     ovs_strlcpy(pp->name, opp->name, OFP_MAX_PORT_NAME_LEN);
2156
2157     pp->config = ntohl(opp->config) & OFPPC10_ALL;
2158     pp->state = ntohl(opp->state) & OFPPS10_ALL;
2159
2160     pp->curr = netdev_port_features_from_ofp10(opp->curr);
2161     pp->advertised = netdev_port_features_from_ofp10(opp->advertised);
2162     pp->supported = netdev_port_features_from_ofp10(opp->supported);
2163     pp->peer = netdev_port_features_from_ofp10(opp->peer);
2164
2165     pp->curr_speed = netdev_features_to_bps(pp->curr) / 1000;
2166     pp->max_speed = netdev_features_to_bps(pp->supported) / 1000;
2167
2168     return 0;
2169 }
2170
2171 static enum ofperr
2172 ofputil_decode_ofp11_port(struct ofputil_phy_port *pp,
2173                           const struct ofp11_port *op)
2174 {
2175     enum ofperr error;
2176
2177     memset(pp, 0, sizeof *pp);
2178
2179     error = ofputil_port_from_ofp11(op->port_no, &pp->port_no);
2180     if (error) {
2181         return error;
2182     }
2183     memcpy(pp->hw_addr, op->hw_addr, OFP_ETH_ALEN);
2184     ovs_strlcpy(pp->name, op->name, OFP_MAX_PORT_NAME_LEN);
2185
2186     pp->config = ntohl(op->config) & OFPPC11_ALL;
2187     pp->state = ntohl(op->state) & OFPPC11_ALL;
2188
2189     pp->curr = netdev_port_features_from_ofp11(op->curr);
2190     pp->advertised = netdev_port_features_from_ofp11(op->advertised);
2191     pp->supported = netdev_port_features_from_ofp11(op->supported);
2192     pp->peer = netdev_port_features_from_ofp11(op->peer);
2193
2194     pp->curr_speed = ntohl(op->curr_speed);
2195     pp->max_speed = ntohl(op->max_speed);
2196
2197     return 0;
2198 }
2199
2200 static size_t
2201 ofputil_get_phy_port_size(enum ofp_version ofp_version)
2202 {
2203     switch (ofp_version) {
2204     case OFP10_VERSION:
2205         return sizeof(struct ofp10_phy_port);
2206     case OFP11_VERSION:
2207     case OFP12_VERSION:
2208         return sizeof(struct ofp11_port);
2209     default:
2210         NOT_REACHED();
2211     }
2212 }
2213
2214 static void
2215 ofputil_encode_ofp10_phy_port(const struct ofputil_phy_port *pp,
2216                               struct ofp10_phy_port *opp)
2217 {
2218     memset(opp, 0, sizeof *opp);
2219
2220     opp->port_no = htons(pp->port_no);
2221     memcpy(opp->hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2222     ovs_strlcpy(opp->name, pp->name, OFP_MAX_PORT_NAME_LEN);
2223
2224     opp->config = htonl(pp->config & OFPPC10_ALL);
2225     opp->state = htonl(pp->state & OFPPS10_ALL);
2226
2227     opp->curr = netdev_port_features_to_ofp10(pp->curr);
2228     opp->advertised = netdev_port_features_to_ofp10(pp->advertised);
2229     opp->supported = netdev_port_features_to_ofp10(pp->supported);
2230     opp->peer = netdev_port_features_to_ofp10(pp->peer);
2231 }
2232
2233 static void
2234 ofputil_encode_ofp11_port(const struct ofputil_phy_port *pp,
2235                           struct ofp11_port *op)
2236 {
2237     memset(op, 0, sizeof *op);
2238
2239     op->port_no = ofputil_port_to_ofp11(pp->port_no);
2240     memcpy(op->hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2241     ovs_strlcpy(op->name, pp->name, OFP_MAX_PORT_NAME_LEN);
2242
2243     op->config = htonl(pp->config & OFPPC11_ALL);
2244     op->state = htonl(pp->state & OFPPS11_ALL);
2245
2246     op->curr = netdev_port_features_to_ofp11(pp->curr);
2247     op->advertised = netdev_port_features_to_ofp11(pp->advertised);
2248     op->supported = netdev_port_features_to_ofp11(pp->supported);
2249     op->peer = netdev_port_features_to_ofp11(pp->peer);
2250
2251     op->curr_speed = htonl(pp->curr_speed);
2252     op->max_speed = htonl(pp->max_speed);
2253 }
2254
2255 static void
2256 ofputil_put_phy_port(enum ofp_version ofp_version,
2257                      const struct ofputil_phy_port *pp, struct ofpbuf *b)
2258 {
2259     switch (ofp_version) {
2260     case OFP10_VERSION: {
2261         struct ofp10_phy_port *opp;
2262         if (b->size + sizeof *opp <= UINT16_MAX) {
2263             opp = ofpbuf_put_uninit(b, sizeof *opp);
2264             ofputil_encode_ofp10_phy_port(pp, opp);
2265         }
2266         break;
2267     }
2268
2269     case OFP11_VERSION:
2270     case OFP12_VERSION: {
2271         struct ofp11_port *op;
2272         if (b->size + sizeof *op <= UINT16_MAX) {
2273             op = ofpbuf_put_uninit(b, sizeof *op);
2274             ofputil_encode_ofp11_port(pp, op);
2275         }
2276         break;
2277     }
2278
2279     default:
2280         NOT_REACHED();
2281     }
2282 }
2283
2284 void
2285 ofputil_append_port_desc_stats_reply(enum ofp_version ofp_version,
2286                                      const struct ofputil_phy_port *pp,
2287                                      struct list *replies)
2288 {
2289     switch (ofp_version) {
2290     case OFP10_VERSION: {
2291         struct ofp10_phy_port *opp;
2292
2293         opp = ofpmp_append(replies, sizeof *opp);
2294         ofputil_encode_ofp10_phy_port(pp, opp);
2295         break;
2296     }
2297
2298     case OFP11_VERSION:
2299     case OFP12_VERSION: {
2300         struct ofp11_port *op;
2301
2302         op = ofpmp_append(replies, sizeof *op);
2303         ofputil_encode_ofp11_port(pp, op);
2304         break;
2305     }
2306
2307     default:
2308       NOT_REACHED();
2309     }
2310 }
2311 \f
2312 /* ofputil_switch_features */
2313
2314 #define OFPC_COMMON (OFPC_FLOW_STATS | OFPC_TABLE_STATS | OFPC_PORT_STATS | \
2315                      OFPC_IP_REASM | OFPC_QUEUE_STATS)
2316 BUILD_ASSERT_DECL((int) OFPUTIL_C_FLOW_STATS == OFPC_FLOW_STATS);
2317 BUILD_ASSERT_DECL((int) OFPUTIL_C_TABLE_STATS == OFPC_TABLE_STATS);
2318 BUILD_ASSERT_DECL((int) OFPUTIL_C_PORT_STATS == OFPC_PORT_STATS);
2319 BUILD_ASSERT_DECL((int) OFPUTIL_C_IP_REASM == OFPC_IP_REASM);
2320 BUILD_ASSERT_DECL((int) OFPUTIL_C_QUEUE_STATS == OFPC_QUEUE_STATS);
2321 BUILD_ASSERT_DECL((int) OFPUTIL_C_ARP_MATCH_IP == OFPC_ARP_MATCH_IP);
2322
2323 struct ofputil_action_bit_translation {
2324     enum ofputil_action_bitmap ofputil_bit;
2325     int of_bit;
2326 };
2327
2328 static const struct ofputil_action_bit_translation of10_action_bits[] = {
2329     { OFPUTIL_A_OUTPUT,       OFPAT10_OUTPUT },
2330     { OFPUTIL_A_SET_VLAN_VID, OFPAT10_SET_VLAN_VID },
2331     { OFPUTIL_A_SET_VLAN_PCP, OFPAT10_SET_VLAN_PCP },
2332     { OFPUTIL_A_STRIP_VLAN,   OFPAT10_STRIP_VLAN },
2333     { OFPUTIL_A_SET_DL_SRC,   OFPAT10_SET_DL_SRC },
2334     { OFPUTIL_A_SET_DL_DST,   OFPAT10_SET_DL_DST },
2335     { OFPUTIL_A_SET_NW_SRC,   OFPAT10_SET_NW_SRC },
2336     { OFPUTIL_A_SET_NW_DST,   OFPAT10_SET_NW_DST },
2337     { OFPUTIL_A_SET_NW_TOS,   OFPAT10_SET_NW_TOS },
2338     { OFPUTIL_A_SET_TP_SRC,   OFPAT10_SET_TP_SRC },
2339     { OFPUTIL_A_SET_TP_DST,   OFPAT10_SET_TP_DST },
2340     { OFPUTIL_A_ENQUEUE,      OFPAT10_ENQUEUE },
2341     { 0, 0 },
2342 };
2343
2344 static const struct ofputil_action_bit_translation of11_action_bits[] = {
2345     { OFPUTIL_A_OUTPUT,         OFPAT11_OUTPUT },
2346     { OFPUTIL_A_SET_VLAN_VID,   OFPAT11_SET_VLAN_VID },
2347     { OFPUTIL_A_SET_VLAN_PCP,   OFPAT11_SET_VLAN_PCP },
2348     { OFPUTIL_A_SET_DL_SRC,     OFPAT11_SET_DL_SRC },
2349     { OFPUTIL_A_SET_DL_DST,     OFPAT11_SET_DL_DST },
2350     { OFPUTIL_A_SET_NW_SRC,     OFPAT11_SET_NW_SRC },
2351     { OFPUTIL_A_SET_NW_DST,     OFPAT11_SET_NW_DST },
2352     { OFPUTIL_A_SET_NW_TOS,     OFPAT11_SET_NW_TOS },
2353     { OFPUTIL_A_SET_NW_ECN,     OFPAT11_SET_NW_ECN },
2354     { OFPUTIL_A_SET_TP_SRC,     OFPAT11_SET_TP_SRC },
2355     { OFPUTIL_A_SET_TP_DST,     OFPAT11_SET_TP_DST },
2356     { OFPUTIL_A_COPY_TTL_OUT,   OFPAT11_COPY_TTL_OUT },
2357     { OFPUTIL_A_COPY_TTL_IN,    OFPAT11_COPY_TTL_IN },
2358     { OFPUTIL_A_SET_MPLS_LABEL, OFPAT11_SET_MPLS_LABEL },
2359     { OFPUTIL_A_SET_MPLS_TC,    OFPAT11_SET_MPLS_TC },
2360     { OFPUTIL_A_SET_MPLS_TTL,   OFPAT11_SET_MPLS_TTL },
2361     { OFPUTIL_A_DEC_MPLS_TTL,   OFPAT11_DEC_MPLS_TTL },
2362     { OFPUTIL_A_PUSH_VLAN,      OFPAT11_PUSH_VLAN },
2363     { OFPUTIL_A_POP_VLAN,       OFPAT11_POP_VLAN },
2364     { OFPUTIL_A_PUSH_MPLS,      OFPAT11_PUSH_MPLS },
2365     { OFPUTIL_A_POP_MPLS,       OFPAT11_POP_MPLS },
2366     { OFPUTIL_A_SET_QUEUE,      OFPAT11_SET_QUEUE },
2367     { OFPUTIL_A_GROUP,          OFPAT11_GROUP },
2368     { OFPUTIL_A_SET_NW_TTL,     OFPAT11_SET_NW_TTL },
2369     { OFPUTIL_A_DEC_NW_TTL,     OFPAT11_DEC_NW_TTL },
2370     { 0, 0 },
2371 };
2372
2373 static const struct ofputil_action_bit_translation of12_action_bits[] = {
2374     { OFPUTIL_A_OUTPUT,         OFPAT12_OUTPUT },
2375     { OFPUTIL_A_COPY_TTL_OUT,   OFPAT12_COPY_TTL_OUT },
2376     { OFPUTIL_A_COPY_TTL_IN,    OFPAT12_COPY_TTL_IN },
2377     { OFPUTIL_A_SET_MPLS_TTL,   OFPAT12_SET_MPLS_TTL },
2378     { OFPUTIL_A_DEC_MPLS_TTL,   OFPAT12_DEC_MPLS_TTL },
2379     { OFPUTIL_A_PUSH_VLAN,      OFPAT12_PUSH_VLAN },
2380     { OFPUTIL_A_POP_VLAN,       OFPAT12_POP_VLAN },
2381     { OFPUTIL_A_PUSH_MPLS,      OFPAT12_PUSH_MPLS },
2382     { OFPUTIL_A_POP_MPLS,       OFPAT12_POP_MPLS },
2383     { OFPUTIL_A_SET_QUEUE,      OFPAT12_SET_QUEUE },
2384     { OFPUTIL_A_GROUP,          OFPAT12_GROUP },
2385     { OFPUTIL_A_SET_NW_TTL,     OFPAT12_SET_NW_TTL },
2386     { OFPUTIL_A_DEC_NW_TTL,     OFPAT12_DEC_NW_TTL },
2387     { 0, 0 },
2388 };
2389
2390 static enum ofputil_action_bitmap
2391 decode_action_bits(ovs_be32 of_actions,
2392                    const struct ofputil_action_bit_translation *x)
2393 {
2394     enum ofputil_action_bitmap ofputil_actions;
2395
2396     ofputil_actions = 0;
2397     for (; x->ofputil_bit; x++) {
2398         if (of_actions & htonl(1u << x->of_bit)) {
2399             ofputil_actions |= x->ofputil_bit;
2400         }
2401     }
2402     return ofputil_actions;
2403 }
2404
2405 static uint32_t
2406 ofputil_capabilities_mask(enum ofp_version ofp_version)
2407 {
2408     /* Handle capabilities whose bit is unique for all Open Flow versions */
2409     switch (ofp_version) {
2410     case OFP10_VERSION:
2411     case OFP11_VERSION:
2412         return OFPC_COMMON | OFPC_ARP_MATCH_IP;
2413     case OFP12_VERSION:
2414         return OFPC_COMMON | OFPC12_PORT_BLOCKED;
2415     default:
2416         /* Caller needs to check osf->header.version itself */
2417         return 0;
2418     }
2419 }
2420
2421 /* Decodes an OpenFlow 1.0 or 1.1 "switch_features" structure 'osf' into an
2422  * abstract representation in '*features'.  Initializes '*b' to iterate over
2423  * the OpenFlow port structures following 'osf' with later calls to
2424  * ofputil_pull_phy_port().  Returns 0 if successful, otherwise an
2425  * OFPERR_* value.  */
2426 enum ofperr
2427 ofputil_decode_switch_features(const struct ofp_header *oh,
2428                                struct ofputil_switch_features *features,
2429                                struct ofpbuf *b)
2430 {
2431     const struct ofp_switch_features *osf;
2432     enum ofpraw raw;
2433
2434     ofpbuf_use_const(b, oh, ntohs(oh->length));
2435     raw = ofpraw_pull_assert(b);
2436
2437     osf = ofpbuf_pull(b, sizeof *osf);
2438     features->datapath_id = ntohll(osf->datapath_id);
2439     features->n_buffers = ntohl(osf->n_buffers);
2440     features->n_tables = osf->n_tables;
2441
2442     features->capabilities = ntohl(osf->capabilities) &
2443         ofputil_capabilities_mask(oh->version);
2444
2445     if (b->size % ofputil_get_phy_port_size(oh->version)) {
2446         return OFPERR_OFPBRC_BAD_LEN;
2447     }
2448
2449     if (raw == OFPRAW_OFPT10_FEATURES_REPLY) {
2450         if (osf->capabilities & htonl(OFPC10_STP)) {
2451             features->capabilities |= OFPUTIL_C_STP;
2452         }
2453         features->actions = decode_action_bits(osf->actions, of10_action_bits);
2454     } else if (raw == OFPRAW_OFPT11_FEATURES_REPLY) {
2455         if (osf->capabilities & htonl(OFPC11_GROUP_STATS)) {
2456             features->capabilities |= OFPUTIL_C_GROUP_STATS;
2457         }
2458         switch ((enum ofp_version)oh->version) {
2459         case OFP11_VERSION:
2460             features->actions = decode_action_bits(htonl(UINT32_MAX),
2461                                                    of11_action_bits);
2462             break;
2463         case OFP12_VERSION:
2464             features->actions = decode_action_bits(htonl(UINT32_MAX),
2465                                                    of12_action_bits);
2466             break;
2467         case OFP10_VERSION:
2468         default:
2469             NOT_REACHED();
2470         }
2471     } else {
2472         return OFPERR_OFPBRC_BAD_VERSION;
2473     }
2474
2475     return 0;
2476 }
2477
2478 /* Returns true if the maximum number of ports are in 'oh'. */
2479 static bool
2480 max_ports_in_features(const struct ofp_header *oh)
2481 {
2482     size_t pp_size = ofputil_get_phy_port_size(oh->version);
2483     return ntohs(oh->length) + pp_size > UINT16_MAX;
2484 }
2485
2486 /* Given a buffer 'b' that contains a Features Reply message, checks if
2487  * it contains the maximum number of ports that will fit.  If so, it
2488  * returns true and removes the ports from the message.  The caller
2489  * should then send an OFPST_PORT_DESC stats request to get the ports,
2490  * since the switch may have more ports than could be represented in the
2491  * Features Reply.  Otherwise, returns false.
2492  */
2493 bool
2494 ofputil_switch_features_ports_trunc(struct ofpbuf *b)
2495 {
2496     struct ofp_header *oh = b->data;
2497
2498     if (max_ports_in_features(oh)) {
2499         /* Remove all the ports. */
2500         b->size = (sizeof(struct ofp_header)
2501                    + sizeof(struct ofp_switch_features));
2502         ofpmsg_update_length(b);
2503
2504         return true;
2505     }
2506
2507     return false;
2508 }
2509
2510 static ovs_be32
2511 encode_action_bits(enum ofputil_action_bitmap ofputil_actions,
2512                    const struct ofputil_action_bit_translation *x)
2513 {
2514     uint32_t of_actions;
2515
2516     of_actions = 0;
2517     for (; x->ofputil_bit; x++) {
2518         if (ofputil_actions & x->ofputil_bit) {
2519             of_actions |= 1 << x->of_bit;
2520         }
2521     }
2522     return htonl(of_actions);
2523 }
2524
2525 /* Returns a buffer owned by the caller that encodes 'features' in the format
2526  * required by 'protocol' with the given 'xid'.  The caller should append port
2527  * information to the buffer with subsequent calls to
2528  * ofputil_put_switch_features_port(). */
2529 struct ofpbuf *
2530 ofputil_encode_switch_features(const struct ofputil_switch_features *features,
2531                                enum ofputil_protocol protocol, ovs_be32 xid)
2532 {
2533     struct ofp_switch_features *osf;
2534     struct ofpbuf *b;
2535     enum ofp_version version;
2536     enum ofpraw raw;
2537
2538     version = ofputil_protocol_to_ofp_version(protocol);
2539     switch (version) {
2540     case OFP10_VERSION:
2541         raw = OFPRAW_OFPT10_FEATURES_REPLY;
2542         break;
2543     case OFP11_VERSION:
2544     case OFP12_VERSION:
2545         raw = OFPRAW_OFPT11_FEATURES_REPLY;
2546         break;
2547     default:
2548         NOT_REACHED();
2549     }
2550     b = ofpraw_alloc_xid(raw, version, xid, 0);
2551     osf = ofpbuf_put_zeros(b, sizeof *osf);
2552     osf->datapath_id = htonll(features->datapath_id);
2553     osf->n_buffers = htonl(features->n_buffers);
2554     osf->n_tables = features->n_tables;
2555
2556     osf->capabilities = htonl(features->capabilities & OFPC_COMMON);
2557     osf->capabilities = htonl(features->capabilities &
2558                               ofputil_capabilities_mask(version));
2559     switch (version) {
2560     case OFP10_VERSION:
2561         if (features->capabilities & OFPUTIL_C_STP) {
2562             osf->capabilities |= htonl(OFPC10_STP);
2563         }
2564         osf->actions = encode_action_bits(features->actions, of10_action_bits);
2565         break;
2566     case OFP11_VERSION:
2567     case OFP12_VERSION:
2568         if (features->capabilities & OFPUTIL_C_GROUP_STATS) {
2569             osf->capabilities |= htonl(OFPC11_GROUP_STATS);
2570         }
2571         break;
2572     default:
2573         NOT_REACHED();
2574     }
2575
2576     return b;
2577 }
2578
2579 /* Encodes 'pp' into the format required by the switch_features message already
2580  * in 'b', which should have been returned by ofputil_encode_switch_features(),
2581  * and appends the encoded version to 'b'. */
2582 void
2583 ofputil_put_switch_features_port(const struct ofputil_phy_port *pp,
2584                                  struct ofpbuf *b)
2585 {
2586     const struct ofp_header *oh = b->data;
2587
2588     ofputil_put_phy_port(oh->version, pp, b);
2589 }
2590 \f
2591 /* ofputil_port_status */
2592
2593 /* Decodes the OpenFlow "port status" message in '*ops' into an abstract form
2594  * in '*ps'.  Returns 0 if successful, otherwise an OFPERR_* value. */
2595 enum ofperr
2596 ofputil_decode_port_status(const struct ofp_header *oh,
2597                            struct ofputil_port_status *ps)
2598 {
2599     const struct ofp_port_status *ops;
2600     struct ofpbuf b;
2601     int retval;
2602
2603     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2604     ofpraw_pull_assert(&b);
2605     ops = ofpbuf_pull(&b, sizeof *ops);
2606
2607     if (ops->reason != OFPPR_ADD &&
2608         ops->reason != OFPPR_DELETE &&
2609         ops->reason != OFPPR_MODIFY) {
2610         return OFPERR_NXBRC_BAD_REASON;
2611     }
2612     ps->reason = ops->reason;
2613
2614     retval = ofputil_pull_phy_port(oh->version, &b, &ps->desc);
2615     assert(retval != EOF);
2616     return retval;
2617 }
2618
2619 /* Converts the abstract form of a "port status" message in '*ps' into an
2620  * OpenFlow message suitable for 'protocol', and returns that encoded form in
2621  * a buffer owned by the caller. */
2622 struct ofpbuf *
2623 ofputil_encode_port_status(const struct ofputil_port_status *ps,
2624                            enum ofputil_protocol protocol)
2625 {
2626     struct ofp_port_status *ops;
2627     struct ofpbuf *b;
2628     enum ofp_version version;
2629     enum ofpraw raw;
2630
2631     version = ofputil_protocol_to_ofp_version(protocol);
2632     switch (version) {
2633     case OFP10_VERSION:
2634         raw = OFPRAW_OFPT10_PORT_STATUS;
2635         break;
2636
2637     case OFP11_VERSION:
2638     case OFP12_VERSION:
2639         raw = OFPRAW_OFPT11_PORT_STATUS;
2640         break;
2641
2642     default:
2643         NOT_REACHED();
2644     }
2645
2646     b = ofpraw_alloc_xid(raw, version, htonl(0), 0);
2647     ops = ofpbuf_put_zeros(b, sizeof *ops);
2648     ops->reason = ps->reason;
2649     ofputil_put_phy_port(version, &ps->desc, b);
2650     ofpmsg_update_length(b);
2651     return b;
2652 }
2653 \f
2654 /* ofputil_port_mod */
2655
2656 /* Decodes the OpenFlow "port mod" message in '*oh' into an abstract form in
2657  * '*pm'.  Returns 0 if successful, otherwise an OFPERR_* value. */
2658 enum ofperr
2659 ofputil_decode_port_mod(const struct ofp_header *oh,
2660                         struct ofputil_port_mod *pm)
2661 {
2662     enum ofpraw raw;
2663     struct ofpbuf b;
2664
2665     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2666     raw = ofpraw_pull_assert(&b);
2667
2668     if (raw == OFPRAW_OFPT10_PORT_MOD) {
2669         const struct ofp10_port_mod *opm = b.data;
2670
2671         pm->port_no = ntohs(opm->port_no);
2672         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
2673         pm->config = ntohl(opm->config) & OFPPC10_ALL;
2674         pm->mask = ntohl(opm->mask) & OFPPC10_ALL;
2675         pm->advertise = netdev_port_features_from_ofp10(opm->advertise);
2676     } else if (raw == OFPRAW_OFPT11_PORT_MOD) {
2677         const struct ofp11_port_mod *opm = b.data;
2678         enum ofperr error;
2679
2680         error = ofputil_port_from_ofp11(opm->port_no, &pm->port_no);
2681         if (error) {
2682             return error;
2683         }
2684
2685         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
2686         pm->config = ntohl(opm->config) & OFPPC11_ALL;
2687         pm->mask = ntohl(opm->mask) & OFPPC11_ALL;
2688         pm->advertise = netdev_port_features_from_ofp11(opm->advertise);
2689     } else {
2690         return OFPERR_OFPBRC_BAD_TYPE;
2691     }
2692
2693     pm->config &= pm->mask;
2694     return 0;
2695 }
2696
2697 /* Converts the abstract form of a "port mod" message in '*pm' into an OpenFlow
2698  * message suitable for 'protocol', and returns that encoded form in a buffer
2699  * owned by the caller. */
2700 struct ofpbuf *
2701 ofputil_encode_port_mod(const struct ofputil_port_mod *pm,
2702                         enum ofputil_protocol protocol)
2703 {
2704     enum ofp_version ofp_version = ofputil_protocol_to_ofp_version(protocol);
2705     struct ofpbuf *b;
2706
2707     switch (ofp_version) {
2708     case OFP10_VERSION: {
2709         struct ofp10_port_mod *opm;
2710
2711         b = ofpraw_alloc(OFPRAW_OFPT10_PORT_MOD, ofp_version, 0);
2712         opm = ofpbuf_put_zeros(b, sizeof *opm);
2713         opm->port_no = htons(pm->port_no);
2714         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
2715         opm->config = htonl(pm->config & OFPPC10_ALL);
2716         opm->mask = htonl(pm->mask & OFPPC10_ALL);
2717         opm->advertise = netdev_port_features_to_ofp10(pm->advertise);
2718         break;
2719     }
2720
2721     case OFP11_VERSION: {
2722         struct ofp11_port_mod *opm;
2723
2724         b = ofpraw_alloc(OFPRAW_OFPT11_PORT_MOD, ofp_version, 0);
2725         opm = ofpbuf_put_zeros(b, sizeof *opm);
2726         opm->port_no = htonl(pm->port_no);
2727         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
2728         opm->config = htonl(pm->config & OFPPC11_ALL);
2729         opm->mask = htonl(pm->mask & OFPPC11_ALL);
2730         opm->advertise = netdev_port_features_to_ofp11(pm->advertise);
2731         break;
2732     }
2733
2734     case OFP12_VERSION:
2735     default:
2736         NOT_REACHED();
2737     }
2738
2739     return b;
2740 }
2741 \f
2742 /* ofputil_flow_monitor_request */
2743
2744 /* Converts an NXST_FLOW_MONITOR request in 'msg' into an abstract
2745  * ofputil_flow_monitor_request in 'rq'.
2746  *
2747  * Multiple NXST_FLOW_MONITOR requests can be packed into a single OpenFlow
2748  * message.  Calling this function multiple times for a single 'msg' iterates
2749  * through the requests.  The caller must initially leave 'msg''s layer
2750  * pointers null and not modify them between calls.
2751  *
2752  * Returns 0 if successful, EOF if no requests were left in this 'msg',
2753  * otherwise an OFPERR_* value. */
2754 int
2755 ofputil_decode_flow_monitor_request(struct ofputil_flow_monitor_request *rq,
2756                                     struct ofpbuf *msg)
2757 {
2758     struct nx_flow_monitor_request *nfmr;
2759     uint16_t flags;
2760
2761     if (!msg->l2) {
2762         msg->l2 = msg->data;
2763         ofpraw_pull_assert(msg);
2764     }
2765
2766     if (!msg->size) {
2767         return EOF;
2768     }
2769
2770     nfmr = ofpbuf_try_pull(msg, sizeof *nfmr);
2771     if (!nfmr) {
2772         VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR request has %zu "
2773                      "leftover bytes at end", msg->size);
2774         return OFPERR_OFPBRC_BAD_LEN;
2775     }
2776
2777     flags = ntohs(nfmr->flags);
2778     if (!(flags & (NXFMF_ADD | NXFMF_DELETE | NXFMF_MODIFY))
2779         || flags & ~(NXFMF_INITIAL | NXFMF_ADD | NXFMF_DELETE
2780                      | NXFMF_MODIFY | NXFMF_ACTIONS | NXFMF_OWN)) {
2781         VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR has bad flags %#"PRIx16,
2782                      flags);
2783         return OFPERR_NXBRC_FM_BAD_FLAGS;
2784     }
2785
2786     if (!is_all_zeros(nfmr->zeros, sizeof nfmr->zeros)) {
2787         return OFPERR_NXBRC_MUST_BE_ZERO;
2788     }
2789
2790     rq->id = ntohl(nfmr->id);
2791     rq->flags = flags;
2792     rq->out_port = ntohs(nfmr->out_port);
2793     rq->table_id = nfmr->table_id;
2794
2795     return nx_pull_match(msg, ntohs(nfmr->match_len), OFP_DEFAULT_PRIORITY,
2796                          &rq->match, NULL, NULL);
2797 }
2798
2799 void
2800 ofputil_append_flow_monitor_request(
2801     const struct ofputil_flow_monitor_request *rq, struct ofpbuf *msg)
2802 {
2803     struct nx_flow_monitor_request *nfmr;
2804     size_t start_ofs;
2805     int match_len;
2806
2807     if (!msg->size) {
2808         ofpraw_put(OFPRAW_NXST_FLOW_MONITOR_REQUEST, OFP10_VERSION, msg);
2809     }
2810
2811     start_ofs = msg->size;
2812     ofpbuf_put_zeros(msg, sizeof *nfmr);
2813     match_len = nx_put_match(msg, false, &rq->match, htonll(0), htonll(0));
2814
2815     nfmr = ofpbuf_at_assert(msg, start_ofs, sizeof *nfmr);
2816     nfmr->id = htonl(rq->id);
2817     nfmr->flags = htons(rq->flags);
2818     nfmr->out_port = htons(rq->out_port);
2819     nfmr->match_len = htons(match_len);
2820     nfmr->table_id = rq->table_id;
2821 }
2822
2823 /* Converts an NXST_FLOW_MONITOR reply (also known as a flow update) in 'msg'
2824  * into an abstract ofputil_flow_update in 'update'.  The caller must have
2825  * initialized update->match to point to space allocated for a cls_rule.
2826  *
2827  * Uses 'ofpacts' to store the abstract OFPACT_* version of the update's
2828  * actions (except for NXFME_ABBREV, which never includes actions).  The caller
2829  * must initialize 'ofpacts' and retains ownership of it.  'update->ofpacts'
2830  * will point into the 'ofpacts' buffer.
2831  *
2832  * Multiple flow updates can be packed into a single OpenFlow message.  Calling
2833  * this function multiple times for a single 'msg' iterates through the
2834  * updates.  The caller must initially leave 'msg''s layer pointers null and
2835  * not modify them between calls.
2836  *
2837  * Returns 0 if successful, EOF if no updates were left in this 'msg',
2838  * otherwise an OFPERR_* value. */
2839 int
2840 ofputil_decode_flow_update(struct ofputil_flow_update *update,
2841                            struct ofpbuf *msg, struct ofpbuf *ofpacts)
2842 {
2843     struct nx_flow_update_header *nfuh;
2844     unsigned int length;
2845
2846     if (!msg->l2) {
2847         msg->l2 = msg->data;
2848         ofpraw_pull_assert(msg);
2849     }
2850
2851     if (!msg->size) {
2852         return EOF;
2853     }
2854
2855     if (msg->size < sizeof(struct nx_flow_update_header)) {
2856         goto bad_len;
2857     }
2858
2859     nfuh = msg->data;
2860     update->event = ntohs(nfuh->event);
2861     length = ntohs(nfuh->length);
2862     if (length > msg->size || length % 8) {
2863         goto bad_len;
2864     }
2865
2866     if (update->event == NXFME_ABBREV) {
2867         struct nx_flow_update_abbrev *nfua;
2868
2869         if (length != sizeof *nfua) {
2870             goto bad_len;
2871         }
2872
2873         nfua = ofpbuf_pull(msg, sizeof *nfua);
2874         update->xid = nfua->xid;
2875         return 0;
2876     } else if (update->event == NXFME_ADDED
2877                || update->event == NXFME_DELETED
2878                || update->event == NXFME_MODIFIED) {
2879         struct nx_flow_update_full *nfuf;
2880         unsigned int actions_len;
2881         unsigned int match_len;
2882         enum ofperr error;
2883
2884         if (length < sizeof *nfuf) {
2885             goto bad_len;
2886         }
2887
2888         nfuf = ofpbuf_pull(msg, sizeof *nfuf);
2889         match_len = ntohs(nfuf->match_len);
2890         if (sizeof *nfuf + match_len > length) {
2891             goto bad_len;
2892         }
2893
2894         update->reason = ntohs(nfuf->reason);
2895         update->idle_timeout = ntohs(nfuf->idle_timeout);
2896         update->hard_timeout = ntohs(nfuf->hard_timeout);
2897         update->table_id = nfuf->table_id;
2898         update->cookie = nfuf->cookie;
2899
2900         error = nx_pull_match(msg, match_len, ntohs(nfuf->priority),
2901                               update->match, NULL, NULL);
2902         if (error) {
2903             return error;
2904         }
2905
2906         actions_len = length - sizeof *nfuf - ROUND_UP(match_len, 8);
2907         error = ofpacts_pull_openflow10(msg, actions_len, ofpacts);
2908         if (error) {
2909             return error;
2910         }
2911
2912         update->ofpacts = ofpacts->data;
2913         update->ofpacts_len = ofpacts->size;
2914         return 0;
2915     } else {
2916         VLOG_WARN_RL(&bad_ofmsg_rl,
2917                      "NXST_FLOW_MONITOR reply has bad event %"PRIu16,
2918                      ntohs(nfuh->event));
2919         return OFPERR_OFPET_BAD_REQUEST;
2920     }
2921
2922 bad_len:
2923     VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR reply has %zu "
2924                  "leftover bytes at end", msg->size);
2925     return OFPERR_OFPBRC_BAD_LEN;
2926 }
2927
2928 uint32_t
2929 ofputil_decode_flow_monitor_cancel(const struct ofp_header *oh)
2930 {
2931     const struct nx_flow_monitor_cancel *cancel = ofpmsg_body(oh);
2932
2933     return ntohl(cancel->id);
2934 }
2935
2936 struct ofpbuf *
2937 ofputil_encode_flow_monitor_cancel(uint32_t id)
2938 {
2939     struct nx_flow_monitor_cancel *nfmc;
2940     struct ofpbuf *msg;
2941
2942     msg = ofpraw_alloc(OFPRAW_NXT_FLOW_MONITOR_CANCEL, OFP10_VERSION, 0);
2943     nfmc = ofpbuf_put_uninit(msg, sizeof *nfmc);
2944     nfmc->id = htonl(id);
2945     return msg;
2946 }
2947
2948 void
2949 ofputil_start_flow_update(struct list *replies)
2950 {
2951     struct ofpbuf *msg;
2952
2953     msg = ofpraw_alloc_xid(OFPRAW_NXST_FLOW_MONITOR_REPLY, OFP10_VERSION,
2954                            htonl(0), 1024);
2955
2956     list_init(replies);
2957     list_push_back(replies, &msg->list_node);
2958 }
2959
2960 void
2961 ofputil_append_flow_update(const struct ofputil_flow_update *update,
2962                            struct list *replies)
2963 {
2964     struct nx_flow_update_header *nfuh;
2965     struct ofpbuf *msg;
2966     size_t start_ofs;
2967
2968     msg = ofpbuf_from_list(list_back(replies));
2969     start_ofs = msg->size;
2970
2971     if (update->event == NXFME_ABBREV) {
2972         struct nx_flow_update_abbrev *nfua;
2973
2974         nfua = ofpbuf_put_zeros(msg, sizeof *nfua);
2975         nfua->xid = update->xid;
2976     } else {
2977         struct nx_flow_update_full *nfuf;
2978         int match_len;
2979
2980         ofpbuf_put_zeros(msg, sizeof *nfuf);
2981         match_len = nx_put_match(msg, false, update->match,
2982                                  htonll(0), htonll(0));
2983         ofpacts_put_openflow10(update->ofpacts, update->ofpacts_len, msg);
2984
2985         nfuf = ofpbuf_at_assert(msg, start_ofs, sizeof *nfuf);
2986         nfuf->reason = htons(update->reason);
2987         nfuf->priority = htons(update->match->priority);
2988         nfuf->idle_timeout = htons(update->idle_timeout);
2989         nfuf->hard_timeout = htons(update->hard_timeout);
2990         nfuf->match_len = htons(match_len);
2991         nfuf->table_id = update->table_id;
2992         nfuf->cookie = update->cookie;
2993     }
2994
2995     nfuh = ofpbuf_at_assert(msg, start_ofs, sizeof *nfuh);
2996     nfuh->length = htons(msg->size - start_ofs);
2997     nfuh->event = htons(update->event);
2998
2999     ofpmp_postappend(replies, start_ofs);
3000 }
3001 \f
3002 struct ofpbuf *
3003 ofputil_encode_packet_out(const struct ofputil_packet_out *po)
3004 {
3005     struct ofp_packet_out *opo;
3006     size_t actions_ofs;
3007     struct ofpbuf *msg;
3008     size_t size;
3009
3010     size = po->ofpacts_len;
3011     if (po->buffer_id == UINT32_MAX) {
3012         size += po->packet_len;
3013     }
3014
3015     msg = ofpraw_alloc(OFPRAW_OFPT10_PACKET_OUT, OFP10_VERSION, size);
3016     ofpbuf_put_zeros(msg, sizeof *opo);
3017     actions_ofs = msg->size;
3018     ofpacts_put_openflow10(po->ofpacts, po->ofpacts_len, msg);
3019
3020     opo = msg->l3;
3021     opo->buffer_id = htonl(po->buffer_id);
3022     opo->in_port = htons(po->in_port);
3023     opo->actions_len = htons(msg->size - actions_ofs);
3024
3025     if (po->buffer_id == UINT32_MAX) {
3026         ofpbuf_put(msg, po->packet, po->packet_len);
3027     }
3028
3029     ofpmsg_update_length(msg);
3030
3031     return msg;
3032 }
3033 \f
3034 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
3035 struct ofpbuf *
3036 make_echo_request(void)
3037 {
3038     return ofpraw_alloc_xid(OFPRAW_OFPT_ECHO_REQUEST, OFP10_VERSION,
3039                             htonl(0), 0);
3040 }
3041
3042 /* Creates and returns an OFPT_ECHO_REPLY message matching the
3043  * OFPT_ECHO_REQUEST message in 'rq'. */
3044 struct ofpbuf *
3045 make_echo_reply(const struct ofp_header *rq)
3046 {
3047     struct ofpbuf rq_buf;
3048     struct ofpbuf *reply;
3049
3050     ofpbuf_use_const(&rq_buf, rq, ntohs(rq->length));
3051     ofpraw_pull_assert(&rq_buf);
3052
3053     reply = ofpraw_alloc_reply(OFPRAW_OFPT_ECHO_REPLY, rq, rq_buf.size);
3054     ofpbuf_put(reply, rq_buf.data, rq_buf.size);
3055     return reply;
3056 }
3057
3058 struct ofpbuf *
3059 ofputil_encode_barrier_request(void)
3060 {
3061     return ofpraw_alloc(OFPRAW_OFPT10_BARRIER_REQUEST, OFP10_VERSION, 0);
3062 }
3063
3064 const char *
3065 ofputil_frag_handling_to_string(enum ofp_config_flags flags)
3066 {
3067     switch (flags & OFPC_FRAG_MASK) {
3068     case OFPC_FRAG_NORMAL:   return "normal";
3069     case OFPC_FRAG_DROP:     return "drop";
3070     case OFPC_FRAG_REASM:    return "reassemble";
3071     case OFPC_FRAG_NX_MATCH: return "nx-match";
3072     }
3073
3074     NOT_REACHED();
3075 }
3076
3077 bool
3078 ofputil_frag_handling_from_string(const char *s, enum ofp_config_flags *flags)
3079 {
3080     if (!strcasecmp(s, "normal")) {
3081         *flags = OFPC_FRAG_NORMAL;
3082     } else if (!strcasecmp(s, "drop")) {
3083         *flags = OFPC_FRAG_DROP;
3084     } else if (!strcasecmp(s, "reassemble")) {
3085         *flags = OFPC_FRAG_REASM;
3086     } else if (!strcasecmp(s, "nx-match")) {
3087         *flags = OFPC_FRAG_NX_MATCH;
3088     } else {
3089         return false;
3090     }
3091     return true;
3092 }
3093
3094 /* Converts the OpenFlow 1.1+ port number 'ofp11_port' into an OpenFlow 1.0
3095  * port number and stores the latter in '*ofp10_port', for the purpose of
3096  * decoding OpenFlow 1.1+ protocol messages.  Returns 0 if successful,
3097  * otherwise an OFPERR_* number.
3098  *
3099  * See the definition of OFP11_MAX for an explanation of the mapping. */
3100 enum ofperr
3101 ofputil_port_from_ofp11(ovs_be32 ofp11_port, uint16_t *ofp10_port)
3102 {
3103     uint32_t ofp11_port_h = ntohl(ofp11_port);
3104
3105     if (ofp11_port_h < OFPP_MAX) {
3106         *ofp10_port = ofp11_port_h;
3107         return 0;
3108     } else if (ofp11_port_h >= OFPP11_MAX) {
3109         *ofp10_port = ofp11_port_h - OFPP11_OFFSET;
3110         return 0;
3111     } else {
3112         VLOG_WARN_RL(&bad_ofmsg_rl, "port %"PRIu32" is outside the supported "
3113                      "range 0 through %d or 0x%"PRIx32" through 0x%"PRIx32,
3114                      ofp11_port_h, OFPP_MAX - 1,
3115                      (uint32_t) OFPP11_MAX, UINT32_MAX);
3116         return OFPERR_OFPBAC_BAD_OUT_PORT;
3117     }
3118 }
3119
3120 /* Returns the OpenFlow 1.1+ port number equivalent to the OpenFlow 1.0 port
3121  * number 'ofp10_port', for encoding OpenFlow 1.1+ protocol messages.
3122  *
3123  * See the definition of OFP11_MAX for an explanation of the mapping. */
3124 ovs_be32
3125 ofputil_port_to_ofp11(uint16_t ofp10_port)
3126 {
3127     return htonl(ofp10_port < OFPP_MAX
3128                  ? ofp10_port
3129                  : ofp10_port + OFPP11_OFFSET);
3130 }
3131
3132 /* Checks that 'port' is a valid output port for the OFPAT10_OUTPUT action, given
3133  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
3134  * 'port' is valid, otherwise an OpenFlow return code. */
3135 enum ofperr
3136 ofputil_check_output_port(uint16_t port, int max_ports)
3137 {
3138     switch (port) {
3139     case OFPP_IN_PORT:
3140     case OFPP_TABLE:
3141     case OFPP_NORMAL:
3142     case OFPP_FLOOD:
3143     case OFPP_ALL:
3144     case OFPP_CONTROLLER:
3145     case OFPP_NONE:
3146     case OFPP_LOCAL:
3147         return 0;
3148
3149     default:
3150         if (port < max_ports) {
3151             return 0;
3152         }
3153         return OFPERR_OFPBAC_BAD_OUT_PORT;
3154     }
3155 }
3156
3157 #define OFPUTIL_NAMED_PORTS                     \
3158         OFPUTIL_NAMED_PORT(IN_PORT)             \
3159         OFPUTIL_NAMED_PORT(TABLE)               \
3160         OFPUTIL_NAMED_PORT(NORMAL)              \
3161         OFPUTIL_NAMED_PORT(FLOOD)               \
3162         OFPUTIL_NAMED_PORT(ALL)                 \
3163         OFPUTIL_NAMED_PORT(CONTROLLER)          \
3164         OFPUTIL_NAMED_PORT(LOCAL)               \
3165         OFPUTIL_NAMED_PORT(NONE)
3166
3167 /* Checks whether 's' is the string representation of an OpenFlow port number,
3168  * either as an integer or a string name (e.g. "LOCAL").  If it is, stores the
3169  * number in '*port' and returns true.  Otherwise, returns false. */
3170 bool
3171 ofputil_port_from_string(const char *name, uint16_t *port)
3172 {
3173     struct pair {
3174         const char *name;
3175         uint16_t value;
3176     };
3177     static const struct pair pairs[] = {
3178 #define OFPUTIL_NAMED_PORT(NAME) {#NAME, OFPP_##NAME},
3179         OFPUTIL_NAMED_PORTS
3180 #undef OFPUTIL_NAMED_PORT
3181     };
3182     static const int n_pairs = ARRAY_SIZE(pairs);
3183     int i;
3184
3185     if (str_to_int(name, 0, &i) && i >= 0 && i < UINT16_MAX) {
3186         *port = i;
3187         return true;
3188     }
3189
3190     for (i = 0; i < n_pairs; i++) {
3191         if (!strcasecmp(name, pairs[i].name)) {
3192             *port = pairs[i].value;
3193             return true;
3194         }
3195     }
3196     return false;
3197 }
3198
3199 /* Appends to 's' a string representation of the OpenFlow port number 'port'.
3200  * Most ports' string representation is just the port number, but for special
3201  * ports, e.g. OFPP_LOCAL, it is the name, e.g. "LOCAL". */
3202 void
3203 ofputil_format_port(uint16_t port, struct ds *s)
3204 {
3205     const char *name;
3206
3207     switch (port) {
3208 #define OFPUTIL_NAMED_PORT(NAME) case OFPP_##NAME: name = #NAME; break;
3209         OFPUTIL_NAMED_PORTS
3210 #undef OFPUTIL_NAMED_PORT
3211
3212     default:
3213         ds_put_format(s, "%"PRIu16, port);
3214         return;
3215     }
3216     ds_put_cstr(s, name);
3217 }
3218
3219 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
3220  * 'ofp_version', tries to pull the first element from the array.  If
3221  * successful, initializes '*pp' with an abstract representation of the
3222  * port and returns 0.  If no ports remain to be decoded, returns EOF.
3223  * On an error, returns a positive OFPERR_* value. */
3224 int
3225 ofputil_pull_phy_port(enum ofp_version ofp_version, struct ofpbuf *b,
3226                       struct ofputil_phy_port *pp)
3227 {
3228     switch (ofp_version) {
3229     case OFP10_VERSION: {
3230         const struct ofp10_phy_port *opp = ofpbuf_try_pull(b, sizeof *opp);
3231         return opp ? ofputil_decode_ofp10_phy_port(pp, opp) : EOF;
3232     }
3233     case OFP11_VERSION:
3234     case OFP12_VERSION: {
3235         const struct ofp11_port *op = ofpbuf_try_pull(b, sizeof *op);
3236         return op ? ofputil_decode_ofp11_port(pp, op) : EOF;
3237     }
3238     default:
3239         NOT_REACHED();
3240     }
3241 }
3242
3243 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
3244  * 'ofp_version', returns the number of elements. */
3245 size_t ofputil_count_phy_ports(uint8_t ofp_version, struct ofpbuf *b)
3246 {
3247     return b->size / ofputil_get_phy_port_size(ofp_version);
3248 }
3249
3250 /* Returns the 'enum ofputil_action_code' corresponding to 'name' (e.g. if
3251  * 'name' is "output" then the return value is OFPUTIL_OFPAT10_OUTPUT), or -1 if
3252  * 'name' is not the name of any action.
3253  *
3254  * ofp-util.def lists the mapping from names to action. */
3255 int
3256 ofputil_action_code_from_name(const char *name)
3257 {
3258     static const char *names[OFPUTIL_N_ACTIONS] = {
3259         NULL,
3260 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)           NAME,
3261 #define OFPAT11_ACTION(ENUM, STRUCT, NAME)           NAME,
3262 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) NAME,
3263 #include "ofp-util.def"
3264     };
3265
3266     const char **p;
3267
3268     for (p = names; p < &names[ARRAY_SIZE(names)]; p++) {
3269         if (*p && !strcasecmp(name, *p)) {
3270             return p - names;
3271         }
3272     }
3273     return -1;
3274 }
3275
3276 /* Appends an action of the type specified by 'code' to 'buf' and returns the
3277  * action.  Initializes the parts of 'action' that identify it as having type
3278  * <ENUM> and length 'sizeof *action' and zeros the rest.  For actions that
3279  * have variable length, the length used and cleared is that of struct
3280  * <STRUCT>.  */
3281 void *
3282 ofputil_put_action(enum ofputil_action_code code, struct ofpbuf *buf)
3283 {
3284     switch (code) {
3285     case OFPUTIL_ACTION_INVALID:
3286         NOT_REACHED();
3287
3288 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                    \
3289     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
3290 #define OFPAT11_ACTION OFPAT10_ACTION
3291 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)        \
3292     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
3293 #include "ofp-util.def"
3294     }
3295     NOT_REACHED();
3296 }
3297
3298 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                        \
3299     void                                                        \
3300     ofputil_init_##ENUM(struct STRUCT *s)                       \
3301     {                                                           \
3302         memset(s, 0, sizeof *s);                                \
3303         s->type = htons(ENUM);                                  \
3304         s->len = htons(sizeof *s);                              \
3305     }                                                           \
3306                                                                 \
3307     struct STRUCT *                                             \
3308     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
3309     {                                                           \
3310         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
3311         ofputil_init_##ENUM(s);                                 \
3312         return s;                                               \
3313     }
3314 #define OFPAT11_ACTION OFPAT10_ACTION
3315 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)            \
3316     void                                                        \
3317     ofputil_init_##ENUM(struct STRUCT *s)                       \
3318     {                                                           \
3319         memset(s, 0, sizeof *s);                                \
3320         s->type = htons(OFPAT10_VENDOR);                        \
3321         s->len = htons(sizeof *s);                              \
3322         s->vendor = htonl(NX_VENDOR_ID);                        \
3323         s->subtype = htons(ENUM);                               \
3324     }                                                           \
3325                                                                 \
3326     struct STRUCT *                                             \
3327     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
3328     {                                                           \
3329         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
3330         ofputil_init_##ENUM(s);                                 \
3331         return s;                                               \
3332     }
3333 #include "ofp-util.def"
3334
3335 /* "Normalizes" the wildcards in 'rule'.  That means:
3336  *
3337  *    1. If the type of level N is known, then only the valid fields for that
3338  *       level may be specified.  For example, ARP does not have a TOS field,
3339  *       so nw_tos must be wildcarded if 'rule' specifies an ARP flow.
3340  *       Similarly, IPv4 does not have any IPv6 addresses, so ipv6_src and
3341  *       ipv6_dst (and other fields) must be wildcarded if 'rule' specifies an
3342  *       IPv4 flow.
3343  *
3344  *    2. If the type of level N is not known (or not understood by Open
3345  *       vSwitch), then no fields at all for that level may be specified.  For
3346  *       example, Open vSwitch does not understand SCTP, an L4 protocol, so the
3347  *       L4 fields tp_src and tp_dst must be wildcarded if 'rule' specifies an
3348  *       SCTP flow.
3349  */
3350 void
3351 ofputil_normalize_rule(struct cls_rule *rule)
3352 {
3353     enum {
3354         MAY_NW_ADDR     = 1 << 0, /* nw_src, nw_dst */
3355         MAY_TP_ADDR     = 1 << 1, /* tp_src, tp_dst */
3356         MAY_NW_PROTO    = 1 << 2, /* nw_proto */
3357         MAY_IPVx        = 1 << 3, /* tos, frag, ttl */
3358         MAY_ARP_SHA     = 1 << 4, /* arp_sha */
3359         MAY_ARP_THA     = 1 << 5, /* arp_tha */
3360         MAY_IPV6        = 1 << 6, /* ipv6_src, ipv6_dst, ipv6_label */
3361         MAY_ND_TARGET   = 1 << 7  /* nd_target */
3362     } may_match;
3363
3364     struct flow_wildcards wc;
3365
3366     /* Figure out what fields may be matched. */
3367     if (rule->flow.dl_type == htons(ETH_TYPE_IP)) {
3368         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_NW_ADDR;
3369         if (rule->flow.nw_proto == IPPROTO_TCP ||
3370             rule->flow.nw_proto == IPPROTO_UDP ||
3371             rule->flow.nw_proto == IPPROTO_ICMP) {
3372             may_match |= MAY_TP_ADDR;
3373         }
3374     } else if (rule->flow.dl_type == htons(ETH_TYPE_IPV6)) {
3375         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_IPV6;
3376         if (rule->flow.nw_proto == IPPROTO_TCP ||
3377             rule->flow.nw_proto == IPPROTO_UDP) {
3378             may_match |= MAY_TP_ADDR;
3379         } else if (rule->flow.nw_proto == IPPROTO_ICMPV6) {
3380             may_match |= MAY_TP_ADDR;
3381             if (rule->flow.tp_src == htons(ND_NEIGHBOR_SOLICIT)) {
3382                 may_match |= MAY_ND_TARGET | MAY_ARP_SHA;
3383             } else if (rule->flow.tp_src == htons(ND_NEIGHBOR_ADVERT)) {
3384                 may_match |= MAY_ND_TARGET | MAY_ARP_THA;
3385             }
3386         }
3387     } else if (rule->flow.dl_type == htons(ETH_TYPE_ARP)) {
3388         may_match = MAY_NW_PROTO | MAY_NW_ADDR | MAY_ARP_SHA | MAY_ARP_THA;
3389     } else {
3390         may_match = 0;
3391     }
3392
3393     /* Clear the fields that may not be matched. */
3394     wc = rule->wc;
3395     if (!(may_match & MAY_NW_ADDR)) {
3396         wc.nw_src_mask = wc.nw_dst_mask = htonl(0);
3397     }
3398     if (!(may_match & MAY_TP_ADDR)) {
3399         wc.tp_src_mask = wc.tp_dst_mask = htons(0);
3400     }
3401     if (!(may_match & MAY_NW_PROTO)) {
3402         wc.wildcards |= FWW_NW_PROTO;
3403     }
3404     if (!(may_match & MAY_IPVx)) {
3405         wc.wildcards |= FWW_NW_DSCP;
3406         wc.wildcards |= FWW_NW_ECN;
3407         wc.wildcards |= FWW_NW_TTL;
3408     }
3409     if (!(may_match & MAY_ARP_SHA)) {
3410         memset(wc.arp_sha_mask, 0, ETH_ADDR_LEN);
3411     }
3412     if (!(may_match & MAY_ARP_THA)) {
3413         memset(wc.arp_tha_mask, 0, ETH_ADDR_LEN);
3414     }
3415     if (!(may_match & MAY_IPV6)) {
3416         wc.ipv6_src_mask = wc.ipv6_dst_mask = in6addr_any;
3417         wc.ipv6_label_mask = htonl(0);
3418     }
3419     if (!(may_match & MAY_ND_TARGET)) {
3420         wc.nd_target_mask = in6addr_any;
3421     }
3422
3423     /* Log any changes. */
3424     if (!flow_wildcards_equal(&wc, &rule->wc)) {
3425         bool log = !VLOG_DROP_INFO(&bad_ofmsg_rl);
3426         char *pre = log ? cls_rule_to_string(rule) : NULL;
3427
3428         rule->wc = wc;
3429         cls_rule_zero_wildcarded_fields(rule);
3430
3431         if (log) {
3432             char *post = cls_rule_to_string(rule);
3433             VLOG_INFO("normalization changed ofp_match, details:");
3434             VLOG_INFO(" pre: %s", pre);
3435             VLOG_INFO("post: %s", post);
3436             free(pre);
3437             free(post);
3438         }
3439     }
3440 }
3441
3442 /* Parses a key or a key-value pair from '*stringp'.
3443  *
3444  * On success: Stores the key into '*keyp'.  Stores the value, if present, into
3445  * '*valuep', otherwise an empty string.  Advances '*stringp' past the end of
3446  * the key-value pair, preparing it for another call.  '*keyp' and '*valuep'
3447  * are substrings of '*stringp' created by replacing some of its bytes by null
3448  * terminators.  Returns true.
3449  *
3450  * If '*stringp' is just white space or commas, sets '*keyp' and '*valuep' to
3451  * NULL and returns false. */
3452 bool
3453 ofputil_parse_key_value(char **stringp, char **keyp, char **valuep)
3454 {
3455     char *pos, *key, *value;
3456     size_t key_len;
3457
3458     pos = *stringp;
3459     pos += strspn(pos, ", \t\r\n");
3460     if (*pos == '\0') {
3461         *keyp = *valuep = NULL;
3462         return false;
3463     }
3464
3465     key = pos;
3466     key_len = strcspn(pos, ":=(, \t\r\n");
3467     if (key[key_len] == ':' || key[key_len] == '=') {
3468         /* The value can be separated by a colon. */
3469         size_t value_len;
3470
3471         value = key + key_len + 1;
3472         value_len = strcspn(value, ", \t\r\n");
3473         pos = value + value_len + (value[value_len] != '\0');
3474         value[value_len] = '\0';
3475     } else if (key[key_len] == '(') {
3476         /* The value can be surrounded by balanced parentheses.  The outermost
3477          * set of parentheses is removed. */
3478         int level = 1;
3479         size_t value_len;
3480
3481         value = key + key_len + 1;
3482         for (value_len = 0; level > 0; value_len++) {
3483             switch (value[value_len]) {
3484             case '\0':
3485                 level = 0;
3486                 break;
3487
3488             case '(':
3489                 level++;
3490                 break;
3491
3492             case ')':
3493                 level--;
3494                 break;
3495             }
3496         }
3497         value[value_len - 1] = '\0';
3498         pos = value + value_len;
3499     } else {
3500         /* There might be no value at all. */
3501         value = key + key_len;  /* Will become the empty string below. */
3502         pos = key + key_len + (key[key_len] != '\0');
3503     }
3504     key[key_len] = '\0';
3505
3506     *stringp = pos;
3507     *keyp = key;
3508     *valuep = value;
3509     return true;
3510 }