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