92d3fe465d2b914e3dc8e4adf5fa3d644a6e4933
[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 ofp10_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 ofp10_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 ofp10_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 ofp10_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 ofp10_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 ofp10_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 matching 'request', 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 ofp_aggregate_stats_reply *asr;
1639     uint64_t packet_count;
1640     uint64_t byte_count;
1641     struct ofpbuf *msg;
1642     enum ofpraw raw;
1643
1644     ofpraw_decode(&raw, request);
1645     if (raw == OFPRAW_OFPST_AGGREGATE_REQUEST) {
1646         packet_count = unknown_to_zero(stats->packet_count);
1647         byte_count = unknown_to_zero(stats->byte_count);
1648     } else {
1649         packet_count = stats->packet_count;
1650         byte_count = stats->byte_count;
1651     }
1652
1653     msg = ofpraw_alloc_stats_reply(request, 0);
1654     asr = ofpbuf_put_zeros(msg, sizeof *asr);
1655     put_32aligned_be64(&asr->packet_count, htonll(packet_count));
1656     put_32aligned_be64(&asr->byte_count, htonll(byte_count));
1657     asr->flow_count = htonl(stats->flow_count);
1658
1659     return msg;
1660 }
1661
1662 enum ofperr
1663 ofputil_decode_aggregate_stats_reply(struct ofputil_aggregate_stats *stats,
1664                                      const struct ofp_header *reply)
1665 {
1666     struct ofp_aggregate_stats_reply *asr;
1667     struct ofpbuf msg;
1668
1669     ofpbuf_use_const(&msg, reply, ntohs(reply->length));
1670     ofpraw_pull_assert(&msg);
1671
1672     asr = msg.l3;
1673     stats->packet_count = ntohll(get_32aligned_be64(&asr->packet_count));
1674     stats->byte_count = ntohll(get_32aligned_be64(&asr->byte_count));
1675     stats->flow_count = ntohl(asr->flow_count);
1676
1677     return 0;
1678 }
1679
1680 /* Converts an OFPT_FLOW_REMOVED or NXT_FLOW_REMOVED message 'oh' into an
1681  * abstract ofputil_flow_removed in 'fr'.  Returns 0 if successful, otherwise
1682  * an OpenFlow error code. */
1683 enum ofperr
1684 ofputil_decode_flow_removed(struct ofputil_flow_removed *fr,
1685                             const struct ofp_header *oh)
1686 {
1687     enum ofpraw raw;
1688     struct ofpbuf b;
1689
1690     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1691     raw = ofpraw_pull_assert(&b);
1692     if (raw == OFPRAW_OFPT10_FLOW_REMOVED) {
1693         const struct ofp_flow_removed *ofr;
1694
1695         ofr = ofpbuf_pull(&b, sizeof *ofr);
1696
1697         ofputil_cls_rule_from_ofp10_match(&ofr->match, ntohs(ofr->priority),
1698                                           &fr->rule);
1699         fr->cookie = ofr->cookie;
1700         fr->reason = ofr->reason;
1701         fr->duration_sec = ntohl(ofr->duration_sec);
1702         fr->duration_nsec = ntohl(ofr->duration_nsec);
1703         fr->idle_timeout = ntohs(ofr->idle_timeout);
1704         fr->packet_count = ntohll(ofr->packet_count);
1705         fr->byte_count = ntohll(ofr->byte_count);
1706     } else if (raw == OFPRAW_NXT_FLOW_REMOVED) {
1707         struct nx_flow_removed *nfr;
1708         int error;
1709
1710         nfr = ofpbuf_pull(&b, sizeof *nfr);
1711         error = nx_pull_match(&b, ntohs(nfr->match_len), ntohs(nfr->priority),
1712                               &fr->rule, NULL, NULL);
1713         if (error) {
1714             return error;
1715         }
1716         if (b.size) {
1717             return OFPERR_OFPBRC_BAD_LEN;
1718         }
1719
1720         fr->cookie = nfr->cookie;
1721         fr->reason = nfr->reason;
1722         fr->duration_sec = ntohl(nfr->duration_sec);
1723         fr->duration_nsec = ntohl(nfr->duration_nsec);
1724         fr->idle_timeout = ntohs(nfr->idle_timeout);
1725         fr->packet_count = ntohll(nfr->packet_count);
1726         fr->byte_count = ntohll(nfr->byte_count);
1727     } else {
1728         NOT_REACHED();
1729     }
1730
1731     return 0;
1732 }
1733
1734 /* Converts abstract ofputil_flow_removed 'fr' into an OFPT_FLOW_REMOVED or
1735  * NXT_FLOW_REMOVED message 'oh' according to 'protocol', and returns the
1736  * message. */
1737 struct ofpbuf *
1738 ofputil_encode_flow_removed(const struct ofputil_flow_removed *fr,
1739                             enum ofputil_protocol protocol)
1740 {
1741     struct ofpbuf *msg;
1742
1743     switch (protocol) {
1744     case OFPUTIL_P_OF10:
1745     case OFPUTIL_P_OF10_TID: {
1746         struct ofp_flow_removed *ofr;
1747
1748         msg = ofpraw_alloc_xid(OFPRAW_OFPT10_FLOW_REMOVED, OFP10_VERSION,
1749                                htonl(0), 0);
1750         ofr = ofpbuf_put_zeros(msg, sizeof *ofr);
1751         ofputil_cls_rule_to_ofp10_match(&fr->rule, &ofr->match);
1752         ofr->cookie = fr->cookie;
1753         ofr->priority = htons(fr->rule.priority);
1754         ofr->reason = fr->reason;
1755         ofr->duration_sec = htonl(fr->duration_sec);
1756         ofr->duration_nsec = htonl(fr->duration_nsec);
1757         ofr->idle_timeout = htons(fr->idle_timeout);
1758         ofr->packet_count = htonll(unknown_to_zero(fr->packet_count));
1759         ofr->byte_count = htonll(unknown_to_zero(fr->byte_count));
1760         break;
1761     }
1762
1763     case OFPUTIL_P_NXM:
1764     case OFPUTIL_P_NXM_TID: {
1765         struct nx_flow_removed *nfr;
1766         int match_len;
1767
1768         msg = ofpraw_alloc_xid(OFPRAW_NXT_FLOW_REMOVED, OFP10_VERSION,
1769                                htonl(0), NXM_TYPICAL_LEN);
1770         nfr = ofpbuf_put_zeros(msg, sizeof *nfr);
1771         match_len = nx_put_match(msg, false, &fr->rule, 0, 0);
1772
1773         nfr = msg->l3;
1774         nfr->cookie = fr->cookie;
1775         nfr->priority = htons(fr->rule.priority);
1776         nfr->reason = fr->reason;
1777         nfr->duration_sec = htonl(fr->duration_sec);
1778         nfr->duration_nsec = htonl(fr->duration_nsec);
1779         nfr->idle_timeout = htons(fr->idle_timeout);
1780         nfr->match_len = htons(match_len);
1781         nfr->packet_count = htonll(fr->packet_count);
1782         nfr->byte_count = htonll(fr->byte_count);
1783         break;
1784     }
1785
1786     case OFPUTIL_P_OF12:
1787     default:
1788         NOT_REACHED();
1789     }
1790
1791     return msg;
1792 }
1793
1794 enum ofperr
1795 ofputil_decode_packet_in(struct ofputil_packet_in *pin,
1796                          const struct ofp_header *oh)
1797 {
1798     enum ofpraw raw;
1799     struct ofpbuf b;
1800
1801     memset(pin, 0, sizeof *pin);
1802
1803     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1804     raw = ofpraw_pull_assert(&b);
1805     if (raw == OFPRAW_OFPT10_PACKET_IN) {
1806         const struct ofp_packet_in *opi;
1807
1808         opi = ofpbuf_pull(&b, offsetof(struct ofp_packet_in, data));
1809
1810         pin->packet = opi->data;
1811         pin->packet_len = b.size;
1812
1813         pin->fmd.in_port = ntohs(opi->in_port);
1814         pin->reason = opi->reason;
1815         pin->buffer_id = ntohl(opi->buffer_id);
1816         pin->total_len = ntohs(opi->total_len);
1817     } else if (raw == OFPRAW_NXT_PACKET_IN) {
1818         const struct nx_packet_in *npi;
1819         struct cls_rule rule;
1820         int error;
1821
1822         npi = ofpbuf_pull(&b, sizeof *npi);
1823         error = nx_pull_match_loose(&b, ntohs(npi->match_len), 0, &rule, NULL,
1824                                     NULL);
1825         if (error) {
1826             return error;
1827         }
1828
1829         if (!ofpbuf_try_pull(&b, 2)) {
1830             return OFPERR_OFPBRC_BAD_LEN;
1831         }
1832
1833         pin->packet = b.data;
1834         pin->packet_len = b.size;
1835         pin->reason = npi->reason;
1836         pin->table_id = npi->table_id;
1837         pin->cookie = npi->cookie;
1838
1839         pin->fmd.in_port = rule.flow.in_port;
1840
1841         pin->fmd.tun_id = rule.flow.tun_id;
1842         pin->fmd.tun_id_mask = rule.wc.tun_id_mask;
1843
1844         pin->fmd.metadata = rule.flow.metadata;
1845         pin->fmd.metadata_mask = rule.wc.metadata_mask;
1846
1847         memcpy(pin->fmd.regs, rule.flow.regs, sizeof pin->fmd.regs);
1848         memcpy(pin->fmd.reg_masks, rule.wc.reg_masks,
1849                sizeof pin->fmd.reg_masks);
1850
1851         pin->buffer_id = ntohl(npi->buffer_id);
1852         pin->total_len = ntohs(npi->total_len);
1853     } else {
1854         NOT_REACHED();
1855     }
1856
1857     return 0;
1858 }
1859
1860 /* Converts abstract ofputil_packet_in 'pin' into a PACKET_IN message
1861  * in the format specified by 'packet_in_format'.  */
1862 struct ofpbuf *
1863 ofputil_encode_packet_in(const struct ofputil_packet_in *pin,
1864                          enum nx_packet_in_format packet_in_format)
1865 {
1866     size_t send_len = MIN(pin->send_len, pin->packet_len);
1867     struct ofpbuf *packet;
1868
1869     /* Add OFPT_PACKET_IN. */
1870     if (packet_in_format == NXPIF_OPENFLOW10) {
1871         struct ofp_packet_in *opi;
1872
1873         packet = ofpraw_alloc_xid(OFPRAW_OFPT10_PACKET_IN, OFP10_VERSION,
1874                                   htonl(0), send_len);
1875         opi = ofpbuf_put_zeros(packet, offsetof(struct ofp_packet_in, data));
1876         opi->total_len = htons(pin->total_len);
1877         opi->in_port = htons(pin->fmd.in_port);
1878         opi->reason = pin->reason;
1879         opi->buffer_id = htonl(pin->buffer_id);
1880
1881         ofpbuf_put(packet, pin->packet, send_len);
1882     } else if (packet_in_format == NXPIF_NXM) {
1883         struct nx_packet_in *npi;
1884         struct cls_rule rule;
1885         size_t match_len;
1886         size_t i;
1887
1888         cls_rule_init_catchall(&rule, 0);
1889         cls_rule_set_tun_id_masked(&rule, pin->fmd.tun_id,
1890                                    pin->fmd.tun_id_mask);
1891         cls_rule_set_metadata_masked(&rule, pin->fmd.metadata,
1892                                    pin->fmd.metadata_mask);
1893
1894
1895         for (i = 0; i < FLOW_N_REGS; i++) {
1896             cls_rule_set_reg_masked(&rule, i, pin->fmd.regs[i],
1897                                     pin->fmd.reg_masks[i]);
1898         }
1899
1900         cls_rule_set_in_port(&rule, pin->fmd.in_port);
1901
1902         /* The final argument is just an estimate of the space required. */
1903         packet = ofpraw_alloc_xid(OFPRAW_NXT_PACKET_IN, OFP10_VERSION,
1904                                   htonl(0), (sizeof(struct flow_metadata) * 2
1905                                              + 2 + send_len));
1906         ofpbuf_put_zeros(packet, sizeof *npi);
1907         match_len = nx_put_match(packet, false, &rule, 0, 0);
1908         ofpbuf_put_zeros(packet, 2);
1909         ofpbuf_put(packet, pin->packet, send_len);
1910
1911         npi = packet->l3;
1912         npi->buffer_id = htonl(pin->buffer_id);
1913         npi->total_len = htons(pin->total_len);
1914         npi->reason = pin->reason;
1915         npi->table_id = pin->table_id;
1916         npi->cookie = pin->cookie;
1917         npi->match_len = htons(match_len);
1918     } else {
1919         NOT_REACHED();
1920     }
1921     ofpmsg_update_length(packet);
1922
1923     return packet;
1924 }
1925
1926 const char *
1927 ofputil_packet_in_reason_to_string(enum ofp_packet_in_reason reason)
1928 {
1929     static char s[INT_STRLEN(int) + 1];
1930
1931     switch (reason) {
1932     case OFPR_NO_MATCH:
1933         return "no_match";
1934     case OFPR_ACTION:
1935         return "action";
1936     case OFPR_INVALID_TTL:
1937         return "invalid_ttl";
1938
1939     case OFPR_N_REASONS:
1940     default:
1941         sprintf(s, "%d", (int) reason);
1942         return s;
1943     }
1944 }
1945
1946 bool
1947 ofputil_packet_in_reason_from_string(const char *s,
1948                                      enum ofp_packet_in_reason *reason)
1949 {
1950     int i;
1951
1952     for (i = 0; i < OFPR_N_REASONS; i++) {
1953         if (!strcasecmp(s, ofputil_packet_in_reason_to_string(i))) {
1954             *reason = i;
1955             return true;
1956         }
1957     }
1958     return false;
1959 }
1960
1961 /* Converts an OFPT_PACKET_OUT in 'opo' into an abstract ofputil_packet_out in
1962  * 'po'.
1963  *
1964  * Uses 'ofpacts' to store the abstract OFPACT_* version of the packet out
1965  * message's actions.  The caller must initialize 'ofpacts' and retains
1966  * ownership of it.  'po->ofpacts' will point into the 'ofpacts' buffer.
1967  *
1968  * Returns 0 if successful, otherwise an OFPERR_* value. */
1969 enum ofperr
1970 ofputil_decode_packet_out(struct ofputil_packet_out *po,
1971                           const struct ofp_header *oh,
1972                           struct ofpbuf *ofpacts)
1973 {
1974     const struct ofp_packet_out *opo;
1975     enum ofperr error;
1976     enum ofpraw raw;
1977     struct ofpbuf b;
1978
1979     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1980     raw = ofpraw_pull_assert(&b);
1981     assert(raw == OFPRAW_OFPT10_PACKET_OUT);
1982
1983     opo = ofpbuf_pull(&b, sizeof *opo);
1984     po->buffer_id = ntohl(opo->buffer_id);
1985     po->in_port = ntohs(opo->in_port);
1986     if (po->in_port >= OFPP_MAX && po->in_port != OFPP_LOCAL
1987         && po->in_port != OFPP_NONE && po->in_port != OFPP_CONTROLLER) {
1988         VLOG_WARN_RL(&bad_ofmsg_rl, "packet-out has bad input port %#"PRIx16,
1989                      po->in_port);
1990         return OFPERR_NXBRC_BAD_IN_PORT;
1991     }
1992
1993     error = ofpacts_pull_openflow10(&b, ntohs(opo->actions_len), ofpacts);
1994     if (error) {
1995         return error;
1996     }
1997     po->ofpacts = ofpacts->data;
1998     po->ofpacts_len = ofpacts->size;
1999
2000     if (po->buffer_id == UINT32_MAX) {
2001         po->packet = b.data;
2002         po->packet_len = b.size;
2003     } else {
2004         po->packet = NULL;
2005         po->packet_len = 0;
2006     }
2007
2008     return 0;
2009 }
2010 \f
2011 /* ofputil_phy_port */
2012
2013 /* NETDEV_F_* to and from OFPPF_* and OFPPF10_*. */
2014 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_HD    == OFPPF_10MB_HD);  /* bit 0 */
2015 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_FD    == OFPPF_10MB_FD);  /* bit 1 */
2016 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_HD   == OFPPF_100MB_HD); /* bit 2 */
2017 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_FD   == OFPPF_100MB_FD); /* bit 3 */
2018 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_HD     == OFPPF_1GB_HD);   /* bit 4 */
2019 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_FD     == OFPPF_1GB_FD);   /* bit 5 */
2020 BUILD_ASSERT_DECL((int) NETDEV_F_10GB_FD    == OFPPF_10GB_FD);  /* bit 6 */
2021
2022 /* NETDEV_F_ bits 11...15 are OFPPF10_ bits 7...11: */
2023 BUILD_ASSERT_DECL((int) NETDEV_F_COPPER == (OFPPF10_COPPER << 4));
2024 BUILD_ASSERT_DECL((int) NETDEV_F_FIBER == (OFPPF10_FIBER << 4));
2025 BUILD_ASSERT_DECL((int) NETDEV_F_AUTONEG == (OFPPF10_AUTONEG << 4));
2026 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE == (OFPPF10_PAUSE << 4));
2027 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE_ASYM == (OFPPF10_PAUSE_ASYM << 4));
2028
2029 static enum netdev_features
2030 netdev_port_features_from_ofp10(ovs_be32 ofp10_)
2031 {
2032     uint32_t ofp10 = ntohl(ofp10_);
2033     return (ofp10 & 0x7f) | ((ofp10 & 0xf80) << 4);
2034 }
2035
2036 static ovs_be32
2037 netdev_port_features_to_ofp10(enum netdev_features features)
2038 {
2039     return htonl((features & 0x7f) | ((features & 0xf800) >> 4));
2040 }
2041
2042 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_HD    == OFPPF_10MB_HD);     /* bit 0 */
2043 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_FD    == OFPPF_10MB_FD);     /* bit 1 */
2044 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_HD   == OFPPF_100MB_HD);    /* bit 2 */
2045 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_FD   == OFPPF_100MB_FD);    /* bit 3 */
2046 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_HD     == OFPPF_1GB_HD);      /* bit 4 */
2047 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_FD     == OFPPF_1GB_FD);      /* bit 5 */
2048 BUILD_ASSERT_DECL((int) NETDEV_F_10GB_FD    == OFPPF_10GB_FD);     /* bit 6 */
2049 BUILD_ASSERT_DECL((int) NETDEV_F_40GB_FD    == OFPPF11_40GB_FD);   /* bit 7 */
2050 BUILD_ASSERT_DECL((int) NETDEV_F_100GB_FD   == OFPPF11_100GB_FD);  /* bit 8 */
2051 BUILD_ASSERT_DECL((int) NETDEV_F_1TB_FD     == OFPPF11_1TB_FD);    /* bit 9 */
2052 BUILD_ASSERT_DECL((int) NETDEV_F_OTHER      == OFPPF11_OTHER);     /* bit 10 */
2053 BUILD_ASSERT_DECL((int) NETDEV_F_COPPER     == OFPPF11_COPPER);    /* bit 11 */
2054 BUILD_ASSERT_DECL((int) NETDEV_F_FIBER      == OFPPF11_FIBER);     /* bit 12 */
2055 BUILD_ASSERT_DECL((int) NETDEV_F_AUTONEG    == OFPPF11_AUTONEG);   /* bit 13 */
2056 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE      == OFPPF11_PAUSE);     /* bit 14 */
2057 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE_ASYM == OFPPF11_PAUSE_ASYM);/* bit 15 */
2058
2059 static enum netdev_features
2060 netdev_port_features_from_ofp11(ovs_be32 ofp11)
2061 {
2062     return ntohl(ofp11) & 0xffff;
2063 }
2064
2065 static ovs_be32
2066 netdev_port_features_to_ofp11(enum netdev_features features)
2067 {
2068     return htonl(features & 0xffff);
2069 }
2070
2071 static enum ofperr
2072 ofputil_decode_ofp10_phy_port(struct ofputil_phy_port *pp,
2073                               const struct ofp10_phy_port *opp)
2074 {
2075     memset(pp, 0, sizeof *pp);
2076
2077     pp->port_no = ntohs(opp->port_no);
2078     memcpy(pp->hw_addr, opp->hw_addr, OFP_ETH_ALEN);
2079     ovs_strlcpy(pp->name, opp->name, OFP_MAX_PORT_NAME_LEN);
2080
2081     pp->config = ntohl(opp->config) & OFPPC10_ALL;
2082     pp->state = ntohl(opp->state) & OFPPS10_ALL;
2083
2084     pp->curr = netdev_port_features_from_ofp10(opp->curr);
2085     pp->advertised = netdev_port_features_from_ofp10(opp->advertised);
2086     pp->supported = netdev_port_features_from_ofp10(opp->supported);
2087     pp->peer = netdev_port_features_from_ofp10(opp->peer);
2088
2089     pp->curr_speed = netdev_features_to_bps(pp->curr) / 1000;
2090     pp->max_speed = netdev_features_to_bps(pp->supported) / 1000;
2091
2092     return 0;
2093 }
2094
2095 static enum ofperr
2096 ofputil_decode_ofp11_port(struct ofputil_phy_port *pp,
2097                           const struct ofp11_port *op)
2098 {
2099     enum ofperr error;
2100
2101     memset(pp, 0, sizeof *pp);
2102
2103     error = ofputil_port_from_ofp11(op->port_no, &pp->port_no);
2104     if (error) {
2105         return error;
2106     }
2107     memcpy(pp->hw_addr, op->hw_addr, OFP_ETH_ALEN);
2108     ovs_strlcpy(pp->name, op->name, OFP_MAX_PORT_NAME_LEN);
2109
2110     pp->config = ntohl(op->config) & OFPPC11_ALL;
2111     pp->state = ntohl(op->state) & OFPPC11_ALL;
2112
2113     pp->curr = netdev_port_features_from_ofp11(op->curr);
2114     pp->advertised = netdev_port_features_from_ofp11(op->advertised);
2115     pp->supported = netdev_port_features_from_ofp11(op->supported);
2116     pp->peer = netdev_port_features_from_ofp11(op->peer);
2117
2118     pp->curr_speed = ntohl(op->curr_speed);
2119     pp->max_speed = ntohl(op->max_speed);
2120
2121     return 0;
2122 }
2123
2124 static size_t
2125 ofputil_get_phy_port_size(uint8_t ofp_version)
2126 {
2127     return ofp_version == OFP10_VERSION ? sizeof(struct ofp10_phy_port)
2128                                         : sizeof(struct ofp11_port);
2129 }
2130
2131 static void
2132 ofputil_encode_ofp10_phy_port(const struct ofputil_phy_port *pp,
2133                               struct ofp10_phy_port *opp)
2134 {
2135     memset(opp, 0, sizeof *opp);
2136
2137     opp->port_no = htons(pp->port_no);
2138     memcpy(opp->hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2139     ovs_strlcpy(opp->name, pp->name, OFP_MAX_PORT_NAME_LEN);
2140
2141     opp->config = htonl(pp->config & OFPPC10_ALL);
2142     opp->state = htonl(pp->state & OFPPS10_ALL);
2143
2144     opp->curr = netdev_port_features_to_ofp10(pp->curr);
2145     opp->advertised = netdev_port_features_to_ofp10(pp->advertised);
2146     opp->supported = netdev_port_features_to_ofp10(pp->supported);
2147     opp->peer = netdev_port_features_to_ofp10(pp->peer);
2148 }
2149
2150 static void
2151 ofputil_encode_ofp11_port(const struct ofputil_phy_port *pp,
2152                           struct ofp11_port *op)
2153 {
2154     memset(op, 0, sizeof *op);
2155
2156     op->port_no = ofputil_port_to_ofp11(pp->port_no);
2157     memcpy(op->hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2158     ovs_strlcpy(op->name, pp->name, OFP_MAX_PORT_NAME_LEN);
2159
2160     op->config = htonl(pp->config & OFPPC11_ALL);
2161     op->state = htonl(pp->state & OFPPS11_ALL);
2162
2163     op->curr = netdev_port_features_to_ofp11(pp->curr);
2164     op->advertised = netdev_port_features_to_ofp11(pp->advertised);
2165     op->supported = netdev_port_features_to_ofp11(pp->supported);
2166     op->peer = netdev_port_features_to_ofp11(pp->peer);
2167
2168     op->curr_speed = htonl(pp->curr_speed);
2169     op->max_speed = htonl(pp->max_speed);
2170 }
2171
2172 static void
2173 ofputil_put_phy_port(uint8_t ofp_version, const struct ofputil_phy_port *pp,
2174                      struct ofpbuf *b)
2175 {
2176     if (ofp_version == OFP10_VERSION) {
2177         struct ofp10_phy_port *opp;
2178         if (b->size + sizeof *opp <= UINT16_MAX) {
2179             opp = ofpbuf_put_uninit(b, sizeof *opp);
2180             ofputil_encode_ofp10_phy_port(pp, opp);
2181         }
2182     } else {
2183         struct ofp11_port *op;
2184         if (b->size + sizeof *op <= UINT16_MAX) {
2185             op = ofpbuf_put_uninit(b, sizeof *op);
2186             ofputil_encode_ofp11_port(pp, op);
2187         }
2188     }
2189 }
2190
2191 void
2192 ofputil_append_port_desc_stats_reply(uint8_t ofp_version,
2193                                      const struct ofputil_phy_port *pp,
2194                                      struct list *replies)
2195 {
2196     if (ofp_version == OFP10_VERSION) {
2197         struct ofp10_phy_port *opp;
2198
2199         opp = ofpmp_append(replies, sizeof *opp);
2200         ofputil_encode_ofp10_phy_port(pp, opp);
2201     } else {
2202         struct ofp11_port *op;
2203
2204         op = ofpmp_append(replies, sizeof *op);
2205         ofputil_encode_ofp11_port(pp, op);
2206     }
2207 }
2208 \f
2209 /* ofputil_switch_features */
2210
2211 #define OFPC_COMMON (OFPC_FLOW_STATS | OFPC_TABLE_STATS | OFPC_PORT_STATS | \
2212                      OFPC_IP_REASM | OFPC_QUEUE_STATS | OFPC_ARP_MATCH_IP)
2213 BUILD_ASSERT_DECL((int) OFPUTIL_C_FLOW_STATS == OFPC_FLOW_STATS);
2214 BUILD_ASSERT_DECL((int) OFPUTIL_C_TABLE_STATS == OFPC_TABLE_STATS);
2215 BUILD_ASSERT_DECL((int) OFPUTIL_C_PORT_STATS == OFPC_PORT_STATS);
2216 BUILD_ASSERT_DECL((int) OFPUTIL_C_IP_REASM == OFPC_IP_REASM);
2217 BUILD_ASSERT_DECL((int) OFPUTIL_C_QUEUE_STATS == OFPC_QUEUE_STATS);
2218 BUILD_ASSERT_DECL((int) OFPUTIL_C_ARP_MATCH_IP == OFPC_ARP_MATCH_IP);
2219
2220 struct ofputil_action_bit_translation {
2221     enum ofputil_action_bitmap ofputil_bit;
2222     int of_bit;
2223 };
2224
2225 static const struct ofputil_action_bit_translation of10_action_bits[] = {
2226     { OFPUTIL_A_OUTPUT,       OFPAT10_OUTPUT },
2227     { OFPUTIL_A_SET_VLAN_VID, OFPAT10_SET_VLAN_VID },
2228     { OFPUTIL_A_SET_VLAN_PCP, OFPAT10_SET_VLAN_PCP },
2229     { OFPUTIL_A_STRIP_VLAN,   OFPAT10_STRIP_VLAN },
2230     { OFPUTIL_A_SET_DL_SRC,   OFPAT10_SET_DL_SRC },
2231     { OFPUTIL_A_SET_DL_DST,   OFPAT10_SET_DL_DST },
2232     { OFPUTIL_A_SET_NW_SRC,   OFPAT10_SET_NW_SRC },
2233     { OFPUTIL_A_SET_NW_DST,   OFPAT10_SET_NW_DST },
2234     { OFPUTIL_A_SET_NW_TOS,   OFPAT10_SET_NW_TOS },
2235     { OFPUTIL_A_SET_TP_SRC,   OFPAT10_SET_TP_SRC },
2236     { OFPUTIL_A_SET_TP_DST,   OFPAT10_SET_TP_DST },
2237     { OFPUTIL_A_ENQUEUE,      OFPAT10_ENQUEUE },
2238     { 0, 0 },
2239 };
2240
2241 static const struct ofputil_action_bit_translation of11_action_bits[] = {
2242     { OFPUTIL_A_OUTPUT,         OFPAT11_OUTPUT },
2243     { OFPUTIL_A_SET_VLAN_VID,   OFPAT11_SET_VLAN_VID },
2244     { OFPUTIL_A_SET_VLAN_PCP,   OFPAT11_SET_VLAN_PCP },
2245     { OFPUTIL_A_SET_DL_SRC,     OFPAT11_SET_DL_SRC },
2246     { OFPUTIL_A_SET_DL_DST,     OFPAT11_SET_DL_DST },
2247     { OFPUTIL_A_SET_NW_SRC,     OFPAT11_SET_NW_SRC },
2248     { OFPUTIL_A_SET_NW_DST,     OFPAT11_SET_NW_DST },
2249     { OFPUTIL_A_SET_NW_TOS,     OFPAT11_SET_NW_TOS },
2250     { OFPUTIL_A_SET_NW_ECN,     OFPAT11_SET_NW_ECN },
2251     { OFPUTIL_A_SET_TP_SRC,     OFPAT11_SET_TP_SRC },
2252     { OFPUTIL_A_SET_TP_DST,     OFPAT11_SET_TP_DST },
2253     { OFPUTIL_A_COPY_TTL_OUT,   OFPAT11_COPY_TTL_OUT },
2254     { OFPUTIL_A_COPY_TTL_IN,    OFPAT11_COPY_TTL_IN },
2255     { OFPUTIL_A_SET_MPLS_LABEL, OFPAT11_SET_MPLS_LABEL },
2256     { OFPUTIL_A_SET_MPLS_TC,    OFPAT11_SET_MPLS_TC },
2257     { OFPUTIL_A_SET_MPLS_TTL,   OFPAT11_SET_MPLS_TTL },
2258     { OFPUTIL_A_DEC_MPLS_TTL,   OFPAT11_DEC_MPLS_TTL },
2259     { OFPUTIL_A_PUSH_VLAN,      OFPAT11_PUSH_VLAN },
2260     { OFPUTIL_A_POP_VLAN,       OFPAT11_POP_VLAN },
2261     { OFPUTIL_A_PUSH_MPLS,      OFPAT11_PUSH_MPLS },
2262     { OFPUTIL_A_POP_MPLS,       OFPAT11_POP_MPLS },
2263     { OFPUTIL_A_SET_QUEUE,      OFPAT11_SET_QUEUE },
2264     { OFPUTIL_A_GROUP,          OFPAT11_GROUP },
2265     { OFPUTIL_A_SET_NW_TTL,     OFPAT11_SET_NW_TTL },
2266     { OFPUTIL_A_DEC_NW_TTL,     OFPAT11_DEC_NW_TTL },
2267     { 0, 0 },
2268 };
2269
2270 static enum ofputil_action_bitmap
2271 decode_action_bits(ovs_be32 of_actions,
2272                    const struct ofputil_action_bit_translation *x)
2273 {
2274     enum ofputil_action_bitmap ofputil_actions;
2275
2276     ofputil_actions = 0;
2277     for (; x->ofputil_bit; x++) {
2278         if (of_actions & htonl(1u << x->of_bit)) {
2279             ofputil_actions |= x->ofputil_bit;
2280         }
2281     }
2282     return ofputil_actions;
2283 }
2284
2285 /* Decodes an OpenFlow 1.0 or 1.1 "switch_features" structure 'osf' into an
2286  * abstract representation in '*features'.  Initializes '*b' to iterate over
2287  * the OpenFlow port structures following 'osf' with later calls to
2288  * ofputil_pull_phy_port().  Returns 0 if successful, otherwise an
2289  * OFPERR_* value.  */
2290 enum ofperr
2291 ofputil_decode_switch_features(const struct ofp_header *oh,
2292                                struct ofputil_switch_features *features,
2293                                struct ofpbuf *b)
2294 {
2295     const struct ofp_switch_features *osf;
2296     enum ofpraw raw;
2297
2298     ofpbuf_use_const(b, oh, ntohs(oh->length));
2299     raw = ofpraw_pull_assert(b);
2300
2301     osf = ofpbuf_pull(b, sizeof *osf);
2302     features->datapath_id = ntohll(osf->datapath_id);
2303     features->n_buffers = ntohl(osf->n_buffers);
2304     features->n_tables = osf->n_tables;
2305
2306     features->capabilities = ntohl(osf->capabilities) & OFPC_COMMON;
2307
2308     if (b->size % ofputil_get_phy_port_size(oh->version)) {
2309         return OFPERR_OFPBRC_BAD_LEN;
2310     }
2311
2312     if (raw == OFPRAW_OFPT10_FEATURES_REPLY) {
2313         if (osf->capabilities & htonl(OFPC10_STP)) {
2314             features->capabilities |= OFPUTIL_C_STP;
2315         }
2316         features->actions = decode_action_bits(osf->actions, of10_action_bits);
2317     } else if (raw == OFPRAW_OFPT11_FEATURES_REPLY) {
2318         if (osf->capabilities & htonl(OFPC11_GROUP_STATS)) {
2319             features->capabilities |= OFPUTIL_C_GROUP_STATS;
2320         }
2321         features->actions = decode_action_bits(osf->actions, of11_action_bits);
2322     } else {
2323         return OFPERR_OFPBRC_BAD_VERSION;
2324     }
2325
2326     return 0;
2327 }
2328
2329 /* Returns true if the maximum number of ports are in 'oh'. */
2330 static bool
2331 max_ports_in_features(const struct ofp_header *oh)
2332 {
2333     size_t pp_size = ofputil_get_phy_port_size(oh->version);
2334     return ntohs(oh->length) + pp_size > UINT16_MAX;
2335 }
2336
2337 /* Given a buffer 'b' that contains a Features Reply message, checks if
2338  * it contains the maximum number of ports that will fit.  If so, it
2339  * returns true and removes the ports from the message.  The caller
2340  * should then send an OFPST_PORT_DESC stats request to get the ports,
2341  * since the switch may have more ports than could be represented in the
2342  * Features Reply.  Otherwise, returns false.
2343  */
2344 bool
2345 ofputil_switch_features_ports_trunc(struct ofpbuf *b)
2346 {
2347     struct ofp_header *oh = b->data;
2348
2349     if (max_ports_in_features(oh)) {
2350         /* Remove all the ports. */
2351         b->size = (sizeof(struct ofp_header)
2352                    + sizeof(struct ofp_switch_features));
2353         ofpmsg_update_length(b);
2354
2355         return true;
2356     }
2357
2358     return false;
2359 }
2360
2361 static ovs_be32
2362 encode_action_bits(enum ofputil_action_bitmap ofputil_actions,
2363                    const struct ofputil_action_bit_translation *x)
2364 {
2365     uint32_t of_actions;
2366
2367     of_actions = 0;
2368     for (; x->ofputil_bit; x++) {
2369         if (ofputil_actions & x->ofputil_bit) {
2370             of_actions |= 1 << x->of_bit;
2371         }
2372     }
2373     return htonl(of_actions);
2374 }
2375
2376 /* Returns a buffer owned by the caller that encodes 'features' in the format
2377  * required by 'protocol' with the given 'xid'.  The caller should append port
2378  * information to the buffer with subsequent calls to
2379  * ofputil_put_switch_features_port(). */
2380 struct ofpbuf *
2381 ofputil_encode_switch_features(const struct ofputil_switch_features *features,
2382                                enum ofputil_protocol protocol, ovs_be32 xid)
2383 {
2384     struct ofp_switch_features *osf;
2385     struct ofpbuf *b;
2386     uint8_t version;
2387
2388     version = ofputil_protocol_to_ofp_version(protocol);
2389     b = ofpraw_alloc_xid(version == OFP10_VERSION
2390                          ? OFPRAW_OFPT10_FEATURES_REPLY
2391                          : OFPRAW_OFPT11_FEATURES_REPLY,
2392                          version, xid, 0);
2393     osf = ofpbuf_put_zeros(b, sizeof *osf);
2394     osf->datapath_id = htonll(features->datapath_id);
2395     osf->n_buffers = htonl(features->n_buffers);
2396     osf->n_tables = features->n_tables;
2397
2398     osf->capabilities = htonl(features->capabilities & OFPC_COMMON);
2399     if (version == OFP10_VERSION) {
2400         if (features->capabilities & OFPUTIL_C_STP) {
2401             osf->capabilities |= htonl(OFPC10_STP);
2402         }
2403         osf->actions = encode_action_bits(features->actions, of10_action_bits);
2404     } else {
2405         if (features->capabilities & OFPUTIL_C_GROUP_STATS) {
2406             osf->capabilities |= htonl(OFPC11_GROUP_STATS);
2407         }
2408         osf->actions = encode_action_bits(features->actions, of11_action_bits);
2409     }
2410
2411     return b;
2412 }
2413
2414 /* Encodes 'pp' into the format required by the switch_features message already
2415  * in 'b', which should have been returned by ofputil_encode_switch_features(),
2416  * and appends the encoded version to 'b'. */
2417 void
2418 ofputil_put_switch_features_port(const struct ofputil_phy_port *pp,
2419                                  struct ofpbuf *b)
2420 {
2421     const struct ofp_header *oh = b->data;
2422
2423     ofputil_put_phy_port(oh->version, pp, b);
2424 }
2425 \f
2426 /* ofputil_port_status */
2427
2428 /* Decodes the OpenFlow "port status" message in '*ops' into an abstract form
2429  * in '*ps'.  Returns 0 if successful, otherwise an OFPERR_* value. */
2430 enum ofperr
2431 ofputil_decode_port_status(const struct ofp_header *oh,
2432                            struct ofputil_port_status *ps)
2433 {
2434     const struct ofp_port_status *ops;
2435     struct ofpbuf b;
2436     int retval;
2437
2438     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2439     ofpraw_pull_assert(&b);
2440     ops = ofpbuf_pull(&b, sizeof *ops);
2441
2442     if (ops->reason != OFPPR_ADD &&
2443         ops->reason != OFPPR_DELETE &&
2444         ops->reason != OFPPR_MODIFY) {
2445         return OFPERR_NXBRC_BAD_REASON;
2446     }
2447     ps->reason = ops->reason;
2448
2449     retval = ofputil_pull_phy_port(oh->version, &b, &ps->desc);
2450     assert(retval != EOF);
2451     return retval;
2452 }
2453
2454 /* Converts the abstract form of a "port status" message in '*ps' into an
2455  * OpenFlow message suitable for 'protocol', and returns that encoded form in
2456  * a buffer owned by the caller. */
2457 struct ofpbuf *
2458 ofputil_encode_port_status(const struct ofputil_port_status *ps,
2459                            enum ofputil_protocol protocol)
2460 {
2461     struct ofp_port_status *ops;
2462     struct ofpbuf *b;
2463     uint8_t version;
2464
2465     version = ofputil_protocol_to_ofp_version(protocol);
2466     b = ofpraw_alloc_xid(version == OFP10_VERSION
2467                          ? OFPRAW_OFPT10_PORT_STATUS
2468                          : OFPRAW_OFPT11_PORT_STATUS,
2469                          version, htonl(0), 0);
2470     ops = ofpbuf_put_zeros(b, sizeof *ops);
2471     ops->reason = ps->reason;
2472     ofputil_put_phy_port(version, &ps->desc, b);
2473     ofpmsg_update_length(b);
2474     return b;
2475 }
2476 \f
2477 /* ofputil_port_mod */
2478
2479 /* Decodes the OpenFlow "port mod" message in '*oh' into an abstract form in
2480  * '*pm'.  Returns 0 if successful, otherwise an OFPERR_* value. */
2481 enum ofperr
2482 ofputil_decode_port_mod(const struct ofp_header *oh,
2483                         struct ofputil_port_mod *pm)
2484 {
2485     enum ofpraw raw;
2486     struct ofpbuf b;
2487
2488     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2489     raw = ofpraw_pull_assert(&b);
2490
2491     if (raw == OFPRAW_OFPT10_PORT_MOD) {
2492         const struct ofp10_port_mod *opm = b.data;
2493
2494         pm->port_no = ntohs(opm->port_no);
2495         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
2496         pm->config = ntohl(opm->config) & OFPPC10_ALL;
2497         pm->mask = ntohl(opm->mask) & OFPPC10_ALL;
2498         pm->advertise = netdev_port_features_from_ofp10(opm->advertise);
2499     } else if (raw == OFPRAW_OFPT11_PORT_MOD) {
2500         const struct ofp11_port_mod *opm = b.data;
2501         enum ofperr error;
2502
2503         error = ofputil_port_from_ofp11(opm->port_no, &pm->port_no);
2504         if (error) {
2505             return error;
2506         }
2507
2508         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
2509         pm->config = ntohl(opm->config) & OFPPC11_ALL;
2510         pm->mask = ntohl(opm->mask) & OFPPC11_ALL;
2511         pm->advertise = netdev_port_features_from_ofp11(opm->advertise);
2512     } else {
2513         return OFPERR_OFPBRC_BAD_TYPE;
2514     }
2515
2516     pm->config &= pm->mask;
2517     return 0;
2518 }
2519
2520 /* Converts the abstract form of a "port mod" message in '*pm' into an OpenFlow
2521  * message suitable for 'protocol', and returns that encoded form in a buffer
2522  * owned by the caller. */
2523 struct ofpbuf *
2524 ofputil_encode_port_mod(const struct ofputil_port_mod *pm,
2525                         enum ofputil_protocol protocol)
2526 {
2527     uint8_t ofp_version = ofputil_protocol_to_ofp_version(protocol);
2528     struct ofpbuf *b;
2529
2530     if (ofp_version == OFP10_VERSION) {
2531         struct ofp10_port_mod *opm;
2532
2533         b = ofpraw_alloc(OFPRAW_OFPT10_PORT_MOD, ofp_version, 0);
2534         opm = ofpbuf_put_zeros(b, sizeof *opm);
2535         opm->port_no = htons(pm->port_no);
2536         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
2537         opm->config = htonl(pm->config & OFPPC10_ALL);
2538         opm->mask = htonl(pm->mask & OFPPC10_ALL);
2539         opm->advertise = netdev_port_features_to_ofp10(pm->advertise);
2540     } else if (ofp_version == OFP11_VERSION) {
2541         struct ofp11_port_mod *opm;
2542
2543         b = ofpraw_alloc(OFPRAW_OFPT11_PORT_MOD, ofp_version, 0);
2544         opm = ofpbuf_put_zeros(b, sizeof *opm);
2545         opm->port_no = htonl(pm->port_no);
2546         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
2547         opm->config = htonl(pm->config & OFPPC11_ALL);
2548         opm->mask = htonl(pm->mask & OFPPC11_ALL);
2549         opm->advertise = netdev_port_features_to_ofp11(pm->advertise);
2550     } else {
2551         NOT_REACHED();
2552     }
2553
2554     return b;
2555 }
2556 \f
2557 /* ofputil_flow_monitor_request */
2558
2559 /* Converts an NXST_FLOW_MONITOR request in 'msg' into an abstract
2560  * ofputil_flow_monitor_request in 'rq'.
2561  *
2562  * Multiple NXST_FLOW_MONITOR requests can be packed into a single OpenFlow
2563  * message.  Calling this function multiple times for a single 'msg' iterates
2564  * through the requests.  The caller must initially leave 'msg''s layer
2565  * pointers null and not modify them between calls.
2566  *
2567  * Returns 0 if successful, EOF if no requests were left in this 'msg',
2568  * otherwise an OFPERR_* value. */
2569 int
2570 ofputil_decode_flow_monitor_request(struct ofputil_flow_monitor_request *rq,
2571                                     struct ofpbuf *msg)
2572 {
2573     struct nx_flow_monitor_request *nfmr;
2574     uint16_t flags;
2575
2576     if (!msg->l2) {
2577         msg->l2 = msg->data;
2578         ofpraw_pull_assert(msg);
2579     }
2580
2581     if (!msg->size) {
2582         return EOF;
2583     }
2584
2585     nfmr = ofpbuf_try_pull(msg, sizeof *nfmr);
2586     if (!nfmr) {
2587         VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR request has %zu "
2588                      "leftover bytes at end", msg->size);
2589         return OFPERR_OFPBRC_BAD_LEN;
2590     }
2591
2592     flags = ntohs(nfmr->flags);
2593     if (!(flags & (NXFMF_ADD | NXFMF_DELETE | NXFMF_MODIFY))
2594         || flags & ~(NXFMF_INITIAL | NXFMF_ADD | NXFMF_DELETE
2595                      | NXFMF_MODIFY | NXFMF_ACTIONS | NXFMF_OWN)) {
2596         VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR has bad flags %#"PRIx16,
2597                      flags);
2598         return OFPERR_NXBRC_FM_BAD_FLAGS;
2599     }
2600
2601     if (!is_all_zeros(nfmr->zeros, sizeof nfmr->zeros)) {
2602         return OFPERR_NXBRC_MUST_BE_ZERO;
2603     }
2604
2605     rq->id = ntohl(nfmr->id);
2606     rq->flags = flags;
2607     rq->out_port = ntohs(nfmr->out_port);
2608     rq->table_id = nfmr->table_id;
2609
2610     return nx_pull_match(msg, ntohs(nfmr->match_len), OFP_DEFAULT_PRIORITY,
2611                          &rq->match, NULL, NULL);
2612 }
2613
2614 void
2615 ofputil_append_flow_monitor_request(
2616     const struct ofputil_flow_monitor_request *rq, struct ofpbuf *msg)
2617 {
2618     struct nx_flow_monitor_request *nfmr;
2619     size_t start_ofs;
2620     int match_len;
2621
2622     if (!msg->size) {
2623         ofpraw_put(OFPRAW_NXST_FLOW_MONITOR_REQUEST, OFP10_VERSION, msg);
2624     }
2625
2626     start_ofs = msg->size;
2627     ofpbuf_put_zeros(msg, sizeof *nfmr);
2628     match_len = nx_put_match(msg, false, &rq->match, htonll(0), htonll(0));
2629
2630     nfmr = ofpbuf_at_assert(msg, start_ofs, sizeof *nfmr);
2631     nfmr->id = htonl(rq->id);
2632     nfmr->flags = htons(rq->flags);
2633     nfmr->out_port = htons(rq->out_port);
2634     nfmr->match_len = htons(match_len);
2635     nfmr->table_id = rq->table_id;
2636 }
2637
2638 /* Converts an NXST_FLOW_MONITOR reply (also known as a flow update) in 'msg'
2639  * into an abstract ofputil_flow_update in 'update'.  The caller must have
2640  * initialized update->match to point to space allocated for a cls_rule.
2641  *
2642  * Uses 'ofpacts' to store the abstract OFPACT_* version of the update's
2643  * actions (except for NXFME_ABBREV, which never includes actions).  The caller
2644  * must initialize 'ofpacts' and retains ownership of it.  'update->ofpacts'
2645  * will point into the 'ofpacts' buffer.
2646  *
2647  * Multiple flow updates can be packed into a single OpenFlow message.  Calling
2648  * this function multiple times for a single 'msg' iterates through the
2649  * updates.  The caller must initially leave 'msg''s layer pointers null and
2650  * not modify them between calls.
2651  *
2652  * Returns 0 if successful, EOF if no updates were left in this 'msg',
2653  * otherwise an OFPERR_* value. */
2654 int
2655 ofputil_decode_flow_update(struct ofputil_flow_update *update,
2656                            struct ofpbuf *msg, struct ofpbuf *ofpacts)
2657 {
2658     struct nx_flow_update_header *nfuh;
2659     unsigned int length;
2660
2661     if (!msg->l2) {
2662         msg->l2 = msg->data;
2663         ofpraw_pull_assert(msg);
2664     }
2665
2666     if (!msg->size) {
2667         return EOF;
2668     }
2669
2670     if (msg->size < sizeof(struct nx_flow_update_header)) {
2671         goto bad_len;
2672     }
2673
2674     nfuh = msg->data;
2675     update->event = ntohs(nfuh->event);
2676     length = ntohs(nfuh->length);
2677     if (length > msg->size || length % 8) {
2678         goto bad_len;
2679     }
2680
2681     if (update->event == NXFME_ABBREV) {
2682         struct nx_flow_update_abbrev *nfua;
2683
2684         if (length != sizeof *nfua) {
2685             goto bad_len;
2686         }
2687
2688         nfua = ofpbuf_pull(msg, sizeof *nfua);
2689         update->xid = nfua->xid;
2690         return 0;
2691     } else if (update->event == NXFME_ADDED
2692                || update->event == NXFME_DELETED
2693                || update->event == NXFME_MODIFIED) {
2694         struct nx_flow_update_full *nfuf;
2695         unsigned int actions_len;
2696         unsigned int match_len;
2697         enum ofperr error;
2698
2699         if (length < sizeof *nfuf) {
2700             goto bad_len;
2701         }
2702
2703         nfuf = ofpbuf_pull(msg, sizeof *nfuf);
2704         match_len = ntohs(nfuf->match_len);
2705         if (sizeof *nfuf + match_len > length) {
2706             goto bad_len;
2707         }
2708
2709         update->reason = ntohs(nfuf->reason);
2710         update->idle_timeout = ntohs(nfuf->idle_timeout);
2711         update->hard_timeout = ntohs(nfuf->hard_timeout);
2712         update->table_id = nfuf->table_id;
2713         update->cookie = nfuf->cookie;
2714
2715         error = nx_pull_match(msg, match_len, ntohs(nfuf->priority),
2716                               update->match, NULL, NULL);
2717         if (error) {
2718             return error;
2719         }
2720
2721         actions_len = length - sizeof *nfuf - ROUND_UP(match_len, 8);
2722         error = ofpacts_pull_openflow10(msg, actions_len, ofpacts);
2723         if (error) {
2724             return error;
2725         }
2726
2727         update->ofpacts = ofpacts->data;
2728         update->ofpacts_len = ofpacts->size;
2729         return 0;
2730     } else {
2731         VLOG_WARN_RL(&bad_ofmsg_rl,
2732                      "NXST_FLOW_MONITOR reply has bad event %"PRIu16,
2733                      ntohs(nfuh->event));
2734         return OFPERR_OFPET_BAD_REQUEST;
2735     }
2736
2737 bad_len:
2738     VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR reply has %zu "
2739                  "leftover bytes at end", msg->size);
2740     return OFPERR_OFPBRC_BAD_LEN;
2741 }
2742
2743 uint32_t
2744 ofputil_decode_flow_monitor_cancel(const struct ofp_header *oh)
2745 {
2746     const struct nx_flow_monitor_cancel *cancel = ofpmsg_body(oh);
2747
2748     return ntohl(cancel->id);
2749 }
2750
2751 struct ofpbuf *
2752 ofputil_encode_flow_monitor_cancel(uint32_t id)
2753 {
2754     struct nx_flow_monitor_cancel *nfmc;
2755     struct ofpbuf *msg;
2756
2757     msg = ofpraw_alloc(OFPRAW_NXT_FLOW_MONITOR_CANCEL, OFP10_VERSION, 0);
2758     nfmc = ofpbuf_put_uninit(msg, sizeof *nfmc);
2759     nfmc->id = htonl(id);
2760     return msg;
2761 }
2762
2763 void
2764 ofputil_start_flow_update(struct list *replies)
2765 {
2766     struct ofpbuf *msg;
2767
2768     msg = ofpraw_alloc_xid(OFPRAW_NXST_FLOW_MONITOR_REPLY, OFP10_VERSION,
2769                            htonl(0), 1024);
2770
2771     list_init(replies);
2772     list_push_back(replies, &msg->list_node);
2773 }
2774
2775 void
2776 ofputil_append_flow_update(const struct ofputil_flow_update *update,
2777                            struct list *replies)
2778 {
2779     struct nx_flow_update_header *nfuh;
2780     struct ofpbuf *msg;
2781     size_t start_ofs;
2782
2783     msg = ofpbuf_from_list(list_back(replies));
2784     start_ofs = msg->size;
2785
2786     if (update->event == NXFME_ABBREV) {
2787         struct nx_flow_update_abbrev *nfua;
2788
2789         nfua = ofpbuf_put_zeros(msg, sizeof *nfua);
2790         nfua->xid = update->xid;
2791     } else {
2792         struct nx_flow_update_full *nfuf;
2793         int match_len;
2794
2795         ofpbuf_put_zeros(msg, sizeof *nfuf);
2796         match_len = nx_put_match(msg, false, update->match,
2797                                  htonll(0), htonll(0));
2798         ofpacts_put_openflow10(update->ofpacts, update->ofpacts_len, msg);
2799
2800         nfuf = ofpbuf_at_assert(msg, start_ofs, sizeof *nfuf);
2801         nfuf->reason = htons(update->reason);
2802         nfuf->priority = htons(update->match->priority);
2803         nfuf->idle_timeout = htons(update->idle_timeout);
2804         nfuf->hard_timeout = htons(update->hard_timeout);
2805         nfuf->match_len = htons(match_len);
2806         nfuf->table_id = update->table_id;
2807         nfuf->cookie = update->cookie;
2808     }
2809
2810     nfuh = ofpbuf_at_assert(msg, start_ofs, sizeof *nfuh);
2811     nfuh->length = htons(msg->size - start_ofs);
2812     nfuh->event = htons(update->event);
2813
2814     ofpmp_postappend(replies, start_ofs);
2815 }
2816 \f
2817 struct ofpbuf *
2818 ofputil_encode_packet_out(const struct ofputil_packet_out *po)
2819 {
2820     struct ofp_packet_out *opo;
2821     size_t actions_ofs;
2822     struct ofpbuf *msg;
2823     size_t size;
2824
2825     size = po->ofpacts_len;
2826     if (po->buffer_id == UINT32_MAX) {
2827         size += po->packet_len;
2828     }
2829
2830     msg = ofpraw_alloc(OFPRAW_OFPT10_PACKET_OUT, OFP10_VERSION, size);
2831     ofpbuf_put_zeros(msg, sizeof *opo);
2832     actions_ofs = msg->size;
2833     ofpacts_put_openflow10(po->ofpacts, po->ofpacts_len, msg);
2834
2835     opo = msg->l3;
2836     opo->buffer_id = htonl(po->buffer_id);
2837     opo->in_port = htons(po->in_port);
2838     opo->actions_len = htons(msg->size - actions_ofs);
2839
2840     if (po->buffer_id == UINT32_MAX) {
2841         ofpbuf_put(msg, po->packet, po->packet_len);
2842     }
2843
2844     ofpmsg_update_length(msg);
2845
2846     return msg;
2847 }
2848 \f
2849 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
2850 struct ofpbuf *
2851 make_echo_request(void)
2852 {
2853     return ofpraw_alloc_xid(OFPRAW_OFPT_ECHO_REQUEST, OFP10_VERSION,
2854                             htonl(0), 0);
2855 }
2856
2857 /* Creates and returns an OFPT_ECHO_REPLY message matching the
2858  * OFPT_ECHO_REQUEST message in 'rq'. */
2859 struct ofpbuf *
2860 make_echo_reply(const struct ofp_header *rq)
2861 {
2862     struct ofpbuf rq_buf;
2863     struct ofpbuf *reply;
2864
2865     ofpbuf_use_const(&rq_buf, rq, ntohs(rq->length));
2866     ofpraw_pull_assert(&rq_buf);
2867
2868     reply = ofpraw_alloc_reply(OFPRAW_OFPT_ECHO_REPLY, rq, rq_buf.size);
2869     ofpbuf_put(reply, rq_buf.data, rq_buf.size);
2870     return reply;
2871 }
2872
2873 struct ofpbuf *
2874 ofputil_encode_barrier_request(void)
2875 {
2876     return ofpraw_alloc(OFPRAW_OFPT10_BARRIER_REQUEST, OFP10_VERSION, 0);
2877 }
2878
2879 const char *
2880 ofputil_frag_handling_to_string(enum ofp_config_flags flags)
2881 {
2882     switch (flags & OFPC_FRAG_MASK) {
2883     case OFPC_FRAG_NORMAL:   return "normal";
2884     case OFPC_FRAG_DROP:     return "drop";
2885     case OFPC_FRAG_REASM:    return "reassemble";
2886     case OFPC_FRAG_NX_MATCH: return "nx-match";
2887     }
2888
2889     NOT_REACHED();
2890 }
2891
2892 bool
2893 ofputil_frag_handling_from_string(const char *s, enum ofp_config_flags *flags)
2894 {
2895     if (!strcasecmp(s, "normal")) {
2896         *flags = OFPC_FRAG_NORMAL;
2897     } else if (!strcasecmp(s, "drop")) {
2898         *flags = OFPC_FRAG_DROP;
2899     } else if (!strcasecmp(s, "reassemble")) {
2900         *flags = OFPC_FRAG_REASM;
2901     } else if (!strcasecmp(s, "nx-match")) {
2902         *flags = OFPC_FRAG_NX_MATCH;
2903     } else {
2904         return false;
2905     }
2906     return true;
2907 }
2908
2909 /* Converts the OpenFlow 1.1+ port number 'ofp11_port' into an OpenFlow 1.0
2910  * port number and stores the latter in '*ofp10_port', for the purpose of
2911  * decoding OpenFlow 1.1+ protocol messages.  Returns 0 if successful,
2912  * otherwise an OFPERR_* number.
2913  *
2914  * See the definition of OFP11_MAX for an explanation of the mapping. */
2915 enum ofperr
2916 ofputil_port_from_ofp11(ovs_be32 ofp11_port, uint16_t *ofp10_port)
2917 {
2918     uint32_t ofp11_port_h = ntohl(ofp11_port);
2919
2920     if (ofp11_port_h < OFPP_MAX) {
2921         *ofp10_port = ofp11_port_h;
2922         return 0;
2923     } else if (ofp11_port_h >= OFPP11_MAX) {
2924         *ofp10_port = ofp11_port_h - OFPP11_OFFSET;
2925         return 0;
2926     } else {
2927         VLOG_WARN_RL(&bad_ofmsg_rl, "port %"PRIu32" is outside the supported "
2928                      "range 0 through %d or 0x%"PRIx32" through 0x%"PRIx32,
2929                      ofp11_port_h, OFPP_MAX - 1,
2930                      (uint32_t) OFPP11_MAX, UINT32_MAX);
2931         return OFPERR_OFPBAC_BAD_OUT_PORT;
2932     }
2933 }
2934
2935 /* Returns the OpenFlow 1.1+ port number equivalent to the OpenFlow 1.0 port
2936  * number 'ofp10_port', for encoding OpenFlow 1.1+ protocol messages.
2937  *
2938  * See the definition of OFP11_MAX for an explanation of the mapping. */
2939 ovs_be32
2940 ofputil_port_to_ofp11(uint16_t ofp10_port)
2941 {
2942     return htonl(ofp10_port < OFPP_MAX
2943                  ? ofp10_port
2944                  : ofp10_port + OFPP11_OFFSET);
2945 }
2946
2947 /* Checks that 'port' is a valid output port for the OFPAT10_OUTPUT action, given
2948  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
2949  * 'port' is valid, otherwise an OpenFlow return code. */
2950 enum ofperr
2951 ofputil_check_output_port(uint16_t port, int max_ports)
2952 {
2953     switch (port) {
2954     case OFPP_IN_PORT:
2955     case OFPP_TABLE:
2956     case OFPP_NORMAL:
2957     case OFPP_FLOOD:
2958     case OFPP_ALL:
2959     case OFPP_CONTROLLER:
2960     case OFPP_NONE:
2961     case OFPP_LOCAL:
2962         return 0;
2963
2964     default:
2965         if (port < max_ports) {
2966             return 0;
2967         }
2968         return OFPERR_OFPBAC_BAD_OUT_PORT;
2969     }
2970 }
2971
2972 #define OFPUTIL_NAMED_PORTS                     \
2973         OFPUTIL_NAMED_PORT(IN_PORT)             \
2974         OFPUTIL_NAMED_PORT(TABLE)               \
2975         OFPUTIL_NAMED_PORT(NORMAL)              \
2976         OFPUTIL_NAMED_PORT(FLOOD)               \
2977         OFPUTIL_NAMED_PORT(ALL)                 \
2978         OFPUTIL_NAMED_PORT(CONTROLLER)          \
2979         OFPUTIL_NAMED_PORT(LOCAL)               \
2980         OFPUTIL_NAMED_PORT(NONE)
2981
2982 /* Checks whether 's' is the string representation of an OpenFlow port number,
2983  * either as an integer or a string name (e.g. "LOCAL").  If it is, stores the
2984  * number in '*port' and returns true.  Otherwise, returns false. */
2985 bool
2986 ofputil_port_from_string(const char *name, uint16_t *port)
2987 {
2988     struct pair {
2989         const char *name;
2990         uint16_t value;
2991     };
2992     static const struct pair pairs[] = {
2993 #define OFPUTIL_NAMED_PORT(NAME) {#NAME, OFPP_##NAME},
2994         OFPUTIL_NAMED_PORTS
2995 #undef OFPUTIL_NAMED_PORT
2996     };
2997     static const int n_pairs = ARRAY_SIZE(pairs);
2998     int i;
2999
3000     if (str_to_int(name, 0, &i) && i >= 0 && i < UINT16_MAX) {
3001         *port = i;
3002         return true;
3003     }
3004
3005     for (i = 0; i < n_pairs; i++) {
3006         if (!strcasecmp(name, pairs[i].name)) {
3007             *port = pairs[i].value;
3008             return true;
3009         }
3010     }
3011     return false;
3012 }
3013
3014 /* Appends to 's' a string representation of the OpenFlow port number 'port'.
3015  * Most ports' string representation is just the port number, but for special
3016  * ports, e.g. OFPP_LOCAL, it is the name, e.g. "LOCAL". */
3017 void
3018 ofputil_format_port(uint16_t port, struct ds *s)
3019 {
3020     const char *name;
3021
3022     switch (port) {
3023 #define OFPUTIL_NAMED_PORT(NAME) case OFPP_##NAME: name = #NAME; break;
3024         OFPUTIL_NAMED_PORTS
3025 #undef OFPUTIL_NAMED_PORT
3026
3027     default:
3028         ds_put_format(s, "%"PRIu16, port);
3029         return;
3030     }
3031     ds_put_cstr(s, name);
3032 }
3033
3034 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
3035  * 'ofp_version', tries to pull the first element from the array.  If
3036  * successful, initializes '*pp' with an abstract representation of the
3037  * port and returns 0.  If no ports remain to be decoded, returns EOF.
3038  * On an error, returns a positive OFPERR_* value. */
3039 int
3040 ofputil_pull_phy_port(uint8_t ofp_version, struct ofpbuf *b,
3041                       struct ofputil_phy_port *pp)
3042 {
3043     if (ofp_version == OFP10_VERSION) {
3044         const struct ofp10_phy_port *opp = ofpbuf_try_pull(b, sizeof *opp);
3045         return opp ? ofputil_decode_ofp10_phy_port(pp, opp) : EOF;
3046     } else {
3047         const struct ofp11_port *op = ofpbuf_try_pull(b, sizeof *op);
3048         return op ? ofputil_decode_ofp11_port(pp, op) : EOF;
3049     }
3050 }
3051
3052 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
3053  * 'ofp_version', returns the number of elements. */
3054 size_t ofputil_count_phy_ports(uint8_t ofp_version, struct ofpbuf *b)
3055 {
3056     return b->size / ofputil_get_phy_port_size(ofp_version);
3057 }
3058
3059 /* Returns the 'enum ofputil_action_code' corresponding to 'name' (e.g. if
3060  * 'name' is "output" then the return value is OFPUTIL_OFPAT10_OUTPUT), or -1 if
3061  * 'name' is not the name of any action.
3062  *
3063  * ofp-util.def lists the mapping from names to action. */
3064 int
3065 ofputil_action_code_from_name(const char *name)
3066 {
3067     static const char *names[OFPUTIL_N_ACTIONS] = {
3068         NULL,
3069 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)           NAME,
3070 #define OFPAT11_ACTION(ENUM, STRUCT, NAME)           NAME,
3071 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) NAME,
3072 #include "ofp-util.def"
3073     };
3074
3075     const char **p;
3076
3077     for (p = names; p < &names[ARRAY_SIZE(names)]; p++) {
3078         if (*p && !strcasecmp(name, *p)) {
3079             return p - names;
3080         }
3081     }
3082     return -1;
3083 }
3084
3085 /* Appends an action of the type specified by 'code' to 'buf' and returns the
3086  * action.  Initializes the parts of 'action' that identify it as having type
3087  * <ENUM> and length 'sizeof *action' and zeros the rest.  For actions that
3088  * have variable length, the length used and cleared is that of struct
3089  * <STRUCT>.  */
3090 void *
3091 ofputil_put_action(enum ofputil_action_code code, struct ofpbuf *buf)
3092 {
3093     switch (code) {
3094     case OFPUTIL_ACTION_INVALID:
3095         NOT_REACHED();
3096
3097 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                    \
3098     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
3099 #define OFPAT11_ACTION OFPAT10_ACTION
3100 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)        \
3101     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
3102 #include "ofp-util.def"
3103     }
3104     NOT_REACHED();
3105 }
3106
3107 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                        \
3108     void                                                        \
3109     ofputil_init_##ENUM(struct STRUCT *s)                       \
3110     {                                                           \
3111         memset(s, 0, sizeof *s);                                \
3112         s->type = htons(ENUM);                                  \
3113         s->len = htons(sizeof *s);                              \
3114     }                                                           \
3115                                                                 \
3116     struct STRUCT *                                             \
3117     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
3118     {                                                           \
3119         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
3120         ofputil_init_##ENUM(s);                                 \
3121         return s;                                               \
3122     }
3123 #define OFPAT11_ACTION OFPAT10_ACTION
3124 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)            \
3125     void                                                        \
3126     ofputil_init_##ENUM(struct STRUCT *s)                       \
3127     {                                                           \
3128         memset(s, 0, sizeof *s);                                \
3129         s->type = htons(OFPAT10_VENDOR);                        \
3130         s->len = htons(sizeof *s);                              \
3131         s->vendor = htonl(NX_VENDOR_ID);                        \
3132         s->subtype = htons(ENUM);                               \
3133     }                                                           \
3134                                                                 \
3135     struct STRUCT *                                             \
3136     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
3137     {                                                           \
3138         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
3139         ofputil_init_##ENUM(s);                                 \
3140         return s;                                               \
3141     }
3142 #include "ofp-util.def"
3143
3144 /* "Normalizes" the wildcards in 'rule'.  That means:
3145  *
3146  *    1. If the type of level N is known, then only the valid fields for that
3147  *       level may be specified.  For example, ARP does not have a TOS field,
3148  *       so nw_tos must be wildcarded if 'rule' specifies an ARP flow.
3149  *       Similarly, IPv4 does not have any IPv6 addresses, so ipv6_src and
3150  *       ipv6_dst (and other fields) must be wildcarded if 'rule' specifies an
3151  *       IPv4 flow.
3152  *
3153  *    2. If the type of level N is not known (or not understood by Open
3154  *       vSwitch), then no fields at all for that level may be specified.  For
3155  *       example, Open vSwitch does not understand SCTP, an L4 protocol, so the
3156  *       L4 fields tp_src and tp_dst must be wildcarded if 'rule' specifies an
3157  *       SCTP flow.
3158  */
3159 void
3160 ofputil_normalize_rule(struct cls_rule *rule)
3161 {
3162     enum {
3163         MAY_NW_ADDR     = 1 << 0, /* nw_src, nw_dst */
3164         MAY_TP_ADDR     = 1 << 1, /* tp_src, tp_dst */
3165         MAY_NW_PROTO    = 1 << 2, /* nw_proto */
3166         MAY_IPVx        = 1 << 3, /* tos, frag, ttl */
3167         MAY_ARP_SHA     = 1 << 4, /* arp_sha */
3168         MAY_ARP_THA     = 1 << 5, /* arp_tha */
3169         MAY_IPV6        = 1 << 6, /* ipv6_src, ipv6_dst, ipv6_label */
3170         MAY_ND_TARGET   = 1 << 7  /* nd_target */
3171     } may_match;
3172
3173     struct flow_wildcards wc;
3174
3175     /* Figure out what fields may be matched. */
3176     if (rule->flow.dl_type == htons(ETH_TYPE_IP)) {
3177         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_NW_ADDR;
3178         if (rule->flow.nw_proto == IPPROTO_TCP ||
3179             rule->flow.nw_proto == IPPROTO_UDP ||
3180             rule->flow.nw_proto == IPPROTO_ICMP) {
3181             may_match |= MAY_TP_ADDR;
3182         }
3183     } else if (rule->flow.dl_type == htons(ETH_TYPE_IPV6)) {
3184         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_IPV6;
3185         if (rule->flow.nw_proto == IPPROTO_TCP ||
3186             rule->flow.nw_proto == IPPROTO_UDP) {
3187             may_match |= MAY_TP_ADDR;
3188         } else if (rule->flow.nw_proto == IPPROTO_ICMPV6) {
3189             may_match |= MAY_TP_ADDR;
3190             if (rule->flow.tp_src == htons(ND_NEIGHBOR_SOLICIT)) {
3191                 may_match |= MAY_ND_TARGET | MAY_ARP_SHA;
3192             } else if (rule->flow.tp_src == htons(ND_NEIGHBOR_ADVERT)) {
3193                 may_match |= MAY_ND_TARGET | MAY_ARP_THA;
3194             }
3195         }
3196     } else if (rule->flow.dl_type == htons(ETH_TYPE_ARP)) {
3197         may_match = MAY_NW_PROTO | MAY_NW_ADDR | MAY_ARP_SHA | MAY_ARP_THA;
3198     } else {
3199         may_match = 0;
3200     }
3201
3202     /* Clear the fields that may not be matched. */
3203     wc = rule->wc;
3204     if (!(may_match & MAY_NW_ADDR)) {
3205         wc.nw_src_mask = wc.nw_dst_mask = htonl(0);
3206     }
3207     if (!(may_match & MAY_TP_ADDR)) {
3208         wc.tp_src_mask = wc.tp_dst_mask = htons(0);
3209     }
3210     if (!(may_match & MAY_NW_PROTO)) {
3211         wc.wildcards |= FWW_NW_PROTO;
3212     }
3213     if (!(may_match & MAY_IPVx)) {
3214         wc.wildcards |= FWW_NW_DSCP;
3215         wc.wildcards |= FWW_NW_ECN;
3216         wc.wildcards |= FWW_NW_TTL;
3217     }
3218     if (!(may_match & MAY_ARP_SHA)) {
3219         memset(wc.arp_sha_mask, 0, ETH_ADDR_LEN);
3220     }
3221     if (!(may_match & MAY_ARP_THA)) {
3222         memset(wc.arp_tha_mask, 0, ETH_ADDR_LEN);
3223     }
3224     if (!(may_match & MAY_IPV6)) {
3225         wc.ipv6_src_mask = wc.ipv6_dst_mask = in6addr_any;
3226         wc.ipv6_label_mask = htonl(0);
3227     }
3228     if (!(may_match & MAY_ND_TARGET)) {
3229         wc.nd_target_mask = in6addr_any;
3230     }
3231
3232     /* Log any changes. */
3233     if (!flow_wildcards_equal(&wc, &rule->wc)) {
3234         bool log = !VLOG_DROP_INFO(&bad_ofmsg_rl);
3235         char *pre = log ? cls_rule_to_string(rule) : NULL;
3236
3237         rule->wc = wc;
3238         cls_rule_zero_wildcarded_fields(rule);
3239
3240         if (log) {
3241             char *post = cls_rule_to_string(rule);
3242             VLOG_INFO("normalization changed ofp_match, details:");
3243             VLOG_INFO(" pre: %s", pre);
3244             VLOG_INFO("post: %s", post);
3245             free(pre);
3246             free(post);
3247         }
3248     }
3249 }
3250
3251 /* Parses a key or a key-value pair from '*stringp'.
3252  *
3253  * On success: Stores the key into '*keyp'.  Stores the value, if present, into
3254  * '*valuep', otherwise an empty string.  Advances '*stringp' past the end of
3255  * the key-value pair, preparing it for another call.  '*keyp' and '*valuep'
3256  * are substrings of '*stringp' created by replacing some of its bytes by null
3257  * terminators.  Returns true.
3258  *
3259  * If '*stringp' is just white space or commas, sets '*keyp' and '*valuep' to
3260  * NULL and returns false. */
3261 bool
3262 ofputil_parse_key_value(char **stringp, char **keyp, char **valuep)
3263 {
3264     char *pos, *key, *value;
3265     size_t key_len;
3266
3267     pos = *stringp;
3268     pos += strspn(pos, ", \t\r\n");
3269     if (*pos == '\0') {
3270         *keyp = *valuep = NULL;
3271         return false;
3272     }
3273
3274     key = pos;
3275     key_len = strcspn(pos, ":=(, \t\r\n");
3276     if (key[key_len] == ':' || key[key_len] == '=') {
3277         /* The value can be separated by a colon. */
3278         size_t value_len;
3279
3280         value = key + key_len + 1;
3281         value_len = strcspn(value, ", \t\r\n");
3282         pos = value + value_len + (value[value_len] != '\0');
3283         value[value_len] = '\0';
3284     } else if (key[key_len] == '(') {
3285         /* The value can be surrounded by balanced parentheses.  The outermost
3286          * set of parentheses is removed. */
3287         int level = 1;
3288         size_t value_len;
3289
3290         value = key + key_len + 1;
3291         for (value_len = 0; level > 0; value_len++) {
3292             switch (value[value_len]) {
3293             case '\0':
3294                 level = 0;
3295                 break;
3296
3297             case '(':
3298                 level++;
3299                 break;
3300
3301             case ')':
3302                 level--;
3303                 break;
3304             }
3305         }
3306         value[value_len - 1] = '\0';
3307         pos = value + value_len;
3308     } else {
3309         /* There might be no value at all. */
3310         value = key + key_len;  /* Will become the empty string below. */
3311         pos = key + key_len + (key[key_len] != '\0');
3312     }
3313     key[key_len] = '\0';
3314
3315     *stringp = pos;
3316     *keyp = key;
3317     *valuep = value;
3318     return true;
3319 }