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