3329ed7ff1a28c3bcff356987d160ef5c24341d8
[sliver-openvswitch.git] / lib / ofp-util.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "ofp-print.h"
19 #include <errno.h>
20 #include <inttypes.h>
21 #include <sys/types.h>
22 #include <netinet/in.h>
23 #include <netinet/icmp6.h>
24 #include <stdlib.h>
25 #include "autopath.h"
26 #include "bundle.h"
27 #include "byte-order.h"
28 #include "classifier.h"
29 #include "dynamic-string.h"
30 #include "learn.h"
31 #include "meta-flow.h"
32 #include "multipath.h"
33 #include "netdev.h"
34 #include "nx-match.h"
35 #include "ofp-errors.h"
36 #include "ofp-util.h"
37 #include "ofpbuf.h"
38 #include "packets.h"
39 #include "random.h"
40 #include "unaligned.h"
41 #include "type-props.h"
42 #include "vlog.h"
43
44 VLOG_DEFINE_THIS_MODULE(ofp_util);
45
46 /* Rate limit for OpenFlow message parse errors.  These always indicate a bug
47  * in the peer and so there's not much point in showing a lot of them. */
48 static struct vlog_rate_limit bad_ofmsg_rl = VLOG_RATE_LIMIT_INIT(1, 5);
49
50 /* Given the wildcard bit count in the least-significant 6 of 'wcbits', returns
51  * an IP netmask with a 1 in each bit that must match and a 0 in each bit that
52  * is wildcarded.
53  *
54  * The bits in 'wcbits' are in the format used in enum ofp_flow_wildcards: 0
55  * is exact match, 1 ignores the LSB, 2 ignores the 2 least-significant bits,
56  * ..., 32 and higher wildcard the entire field.  This is the *opposite* of the
57  * usual convention where e.g. /24 indicates that 8 bits (not 24 bits) are
58  * wildcarded. */
59 ovs_be32
60 ofputil_wcbits_to_netmask(int wcbits)
61 {
62     wcbits &= 0x3f;
63     return wcbits < 32 ? htonl(~((1u << wcbits) - 1)) : 0;
64 }
65
66 /* Given the IP netmask 'netmask', returns the number of bits of the IP address
67  * that it wildcards, that is, the number of 0-bits in 'netmask', a number
68  * between 0 and 32 inclusive.
69  *
70  * If 'netmask' is not a CIDR netmask (see ip_is_cidr()), the return value will
71  * still be in the valid range but isn't otherwise meaningful. */
72 int
73 ofputil_netmask_to_wcbits(ovs_be32 netmask)
74 {
75     return 32 - ip_count_cidr_bits(netmask);
76 }
77
78 /* A list of the FWW_* and OFPFW10_ bits that have the same value, meaning, and
79  * name. */
80 #define WC_INVARIANT_LIST \
81     WC_INVARIANT_BIT(IN_PORT) \
82     WC_INVARIANT_BIT(DL_TYPE) \
83     WC_INVARIANT_BIT(NW_PROTO)
84
85 /* Verify that all of the invariant bits (as defined on WC_INVARIANT_LIST)
86  * actually have the same names and values. */
87 #define WC_INVARIANT_BIT(NAME) BUILD_ASSERT_DECL(FWW_##NAME == OFPFW10_##NAME);
88     WC_INVARIANT_LIST
89 #undef WC_INVARIANT_BIT
90
91 /* WC_INVARIANTS is the invariant bits (as defined on WC_INVARIANT_LIST) all
92  * OR'd together. */
93 static const flow_wildcards_t WC_INVARIANTS = 0
94 #define WC_INVARIANT_BIT(NAME) | FWW_##NAME
95     WC_INVARIANT_LIST
96 #undef WC_INVARIANT_BIT
97 ;
98
99 /* Converts the OpenFlow 1.0 wildcards in 'ofpfw' (OFPFW10_*) into a
100  * flow_wildcards in 'wc' for use in struct cls_rule.  It is the caller's
101  * responsibility to handle the special case where the flow match's dl_vlan is
102  * set to OFP_VLAN_NONE. */
103 void
104 ofputil_wildcard_from_ofpfw10(uint32_t ofpfw, struct flow_wildcards *wc)
105 {
106     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 12);
107
108     /* Initialize most of rule->wc. */
109     flow_wildcards_init_catchall(wc);
110     wc->wildcards = (OVS_FORCE flow_wildcards_t) ofpfw & WC_INVARIANTS;
111
112     /* Wildcard fields that aren't defined by ofp10_match or tun_id. */
113     wc->wildcards |= (FWW_ARP_SHA | FWW_ARP_THA | FWW_NW_ECN | FWW_NW_TTL
114                       | FWW_IPV6_LABEL);
115
116     if (ofpfw & OFPFW10_NW_TOS) {
117         /* OpenFlow 1.0 defines a TOS wildcard, but it's much later in
118          * the enum than we can use. */
119         wc->wildcards |= FWW_NW_DSCP;
120     }
121
122     wc->nw_src_mask = ofputil_wcbits_to_netmask(ofpfw >> OFPFW10_NW_SRC_SHIFT);
123     wc->nw_dst_mask = ofputil_wcbits_to_netmask(ofpfw >> OFPFW10_NW_DST_SHIFT);
124
125     if (!(ofpfw & OFPFW10_TP_SRC)) {
126         wc->tp_src_mask = htons(UINT16_MAX);
127     }
128     if (!(ofpfw & OFPFW10_TP_DST)) {
129         wc->tp_dst_mask = htons(UINT16_MAX);
130     }
131
132     if (!(ofpfw & OFPFW10_DL_SRC)) {
133         memset(wc->dl_src_mask, 0xff, ETH_ADDR_LEN);
134     }
135     if (!(ofpfw & OFPFW10_DL_DST)) {
136         memset(wc->dl_dst_mask, 0xff, ETH_ADDR_LEN);
137     }
138
139     /* VLAN TCI mask. */
140     if (!(ofpfw & OFPFW10_DL_VLAN_PCP)) {
141         wc->vlan_tci_mask |= htons(VLAN_PCP_MASK | VLAN_CFI);
142     }
143     if (!(ofpfw & OFPFW10_DL_VLAN)) {
144         wc->vlan_tci_mask |= htons(VLAN_VID_MASK | VLAN_CFI);
145     }
146 }
147
148 /* Converts the ofp10_match in 'match' into a cls_rule in 'rule', with the
149  * given 'priority'. */
150 void
151 ofputil_cls_rule_from_ofp10_match(const struct ofp10_match *match,
152                                   unsigned int priority, struct cls_rule *rule)
153 {
154     uint32_t ofpfw = ntohl(match->wildcards) & OFPFW10_ALL;
155
156     /* Initialize rule->priority, rule->wc. */
157     rule->priority = !ofpfw ? UINT16_MAX : priority;
158     ofputil_wildcard_from_ofpfw10(ofpfw, &rule->wc);
159
160     /* Initialize most of rule->flow. */
161     rule->flow.nw_src = match->nw_src;
162     rule->flow.nw_dst = match->nw_dst;
163     rule->flow.in_port = ntohs(match->in_port);
164     rule->flow.dl_type = ofputil_dl_type_from_openflow(match->dl_type);
165     rule->flow.tp_src = match->tp_src;
166     rule->flow.tp_dst = match->tp_dst;
167     memcpy(rule->flow.dl_src, match->dl_src, ETH_ADDR_LEN);
168     memcpy(rule->flow.dl_dst, match->dl_dst, ETH_ADDR_LEN);
169     rule->flow.nw_tos = match->nw_tos & IP_DSCP_MASK;
170     rule->flow.nw_proto = match->nw_proto;
171
172     /* Translate VLANs. */
173     if (!(ofpfw & OFPFW10_DL_VLAN) && match->dl_vlan == htons(OFP_VLAN_NONE)) {
174         /* Match only packets without 802.1Q header.
175          *
176          * When OFPFW10_DL_VLAN_PCP is wildcarded, this is obviously correct.
177          *
178          * If OFPFW10_DL_VLAN_PCP is matched, the flow match is contradictory,
179          * because we can't have a specific PCP without an 802.1Q header.
180          * However, older versions of OVS treated this as matching packets
181          * withut an 802.1Q header, so we do here too. */
182         rule->flow.vlan_tci = htons(0);
183         rule->wc.vlan_tci_mask = htons(0xffff);
184     } else {
185         ovs_be16 vid, pcp, tci;
186
187         vid = match->dl_vlan & htons(VLAN_VID_MASK);
188         pcp = htons((match->dl_vlan_pcp << VLAN_PCP_SHIFT) & VLAN_PCP_MASK);
189         tci = vid | pcp | htons(VLAN_CFI);
190         rule->flow.vlan_tci = tci & rule->wc.vlan_tci_mask;
191     }
192
193     /* Clean up. */
194     cls_rule_zero_wildcarded_fields(rule);
195 }
196
197 /* Convert 'rule' into the OpenFlow 1.0 match structure 'match'. */
198 void
199 ofputil_cls_rule_to_ofp10_match(const struct cls_rule *rule,
200                                 struct ofp10_match *match)
201 {
202     const struct flow_wildcards *wc = &rule->wc;
203     uint32_t ofpfw;
204
205     /* Figure out most OpenFlow wildcards. */
206     ofpfw = (OVS_FORCE uint32_t) (wc->wildcards & WC_INVARIANTS);
207     ofpfw |= (ofputil_netmask_to_wcbits(wc->nw_src_mask)
208               << OFPFW10_NW_SRC_SHIFT);
209     ofpfw |= (ofputil_netmask_to_wcbits(wc->nw_dst_mask)
210               << OFPFW10_NW_DST_SHIFT);
211     if (wc->wildcards & FWW_NW_DSCP) {
212         ofpfw |= OFPFW10_NW_TOS;
213     }
214     if (!wc->tp_src_mask) {
215         ofpfw |= OFPFW10_TP_SRC;
216     }
217     if (!wc->tp_dst_mask) {
218         ofpfw |= OFPFW10_TP_DST;
219     }
220     if (eth_addr_is_zero(wc->dl_src_mask)) {
221         ofpfw |= OFPFW10_DL_SRC;
222     }
223     if (eth_addr_is_zero(wc->dl_dst_mask)) {
224         ofpfw |= OFPFW10_DL_DST;
225     }
226
227     /* Translate VLANs. */
228     match->dl_vlan = htons(0);
229     match->dl_vlan_pcp = 0;
230     if (rule->wc.vlan_tci_mask == htons(0)) {
231         ofpfw |= OFPFW10_DL_VLAN | OFPFW10_DL_VLAN_PCP;
232     } else if (rule->wc.vlan_tci_mask & htons(VLAN_CFI)
233                && !(rule->flow.vlan_tci & htons(VLAN_CFI))) {
234         match->dl_vlan = htons(OFP_VLAN_NONE);
235     } else {
236         if (!(rule->wc.vlan_tci_mask & htons(VLAN_VID_MASK))) {
237             ofpfw |= OFPFW10_DL_VLAN;
238         } else {
239             match->dl_vlan = htons(vlan_tci_to_vid(rule->flow.vlan_tci));
240         }
241
242         if (!(rule->wc.vlan_tci_mask & htons(VLAN_PCP_MASK))) {
243             ofpfw |= OFPFW10_DL_VLAN_PCP;
244         } else {
245             match->dl_vlan_pcp = vlan_tci_to_pcp(rule->flow.vlan_tci);
246         }
247     }
248
249     /* Compose most of the match structure. */
250     match->wildcards = htonl(ofpfw);
251     match->in_port = htons(rule->flow.in_port);
252     memcpy(match->dl_src, rule->flow.dl_src, ETH_ADDR_LEN);
253     memcpy(match->dl_dst, rule->flow.dl_dst, ETH_ADDR_LEN);
254     match->dl_type = ofputil_dl_type_to_openflow(rule->flow.dl_type);
255     match->nw_src = rule->flow.nw_src;
256     match->nw_dst = rule->flow.nw_dst;
257     match->nw_tos = rule->flow.nw_tos & IP_DSCP_MASK;
258     match->nw_proto = rule->flow.nw_proto;
259     match->tp_src = rule->flow.tp_src;
260     match->tp_dst = rule->flow.tp_dst;
261     memset(match->pad1, '\0', sizeof match->pad1);
262     memset(match->pad2, '\0', sizeof match->pad2);
263 }
264
265 /* Converts the ofp11_match in 'match' into a cls_rule in 'rule', with the
266  * given 'priority'.  Returns 0 if successful, otherwise an OFPERR_* value. */
267 enum ofperr
268 ofputil_cls_rule_from_ofp11_match(const struct ofp11_match *match,
269                                   unsigned int priority,
270                                   struct cls_rule *rule)
271 {
272     uint16_t wc = ntohl(match->wildcards);
273     uint8_t dl_src_mask[ETH_ADDR_LEN];
274     uint8_t dl_dst_mask[ETH_ADDR_LEN];
275     bool ipv4, arp;
276     int i;
277
278     cls_rule_init_catchall(rule, priority);
279
280     if (!(wc & OFPFW11_IN_PORT)) {
281         uint16_t ofp_port;
282         enum ofperr error;
283
284         error = ofputil_port_from_ofp11(match->in_port, &ofp_port);
285         if (error) {
286             return OFPERR_OFPBMC_BAD_VALUE;
287         }
288         cls_rule_set_in_port(rule, ofp_port);
289     }
290
291     for (i = 0; i < ETH_ADDR_LEN; i++) {
292         dl_src_mask[i] = ~match->dl_src_mask[i];
293     }
294     cls_rule_set_dl_src_masked(rule, match->dl_src, dl_src_mask);
295
296     for (i = 0; i < ETH_ADDR_LEN; i++) {
297         dl_dst_mask[i] = ~match->dl_dst_mask[i];
298     }
299     cls_rule_set_dl_dst_masked(rule, match->dl_dst, dl_dst_mask);
300
301     if (!(wc & OFPFW11_DL_VLAN)) {
302         if (match->dl_vlan == htons(OFPVID11_NONE)) {
303             /* Match only packets without a VLAN tag. */
304             rule->flow.vlan_tci = htons(0);
305             rule->wc.vlan_tci_mask = htons(UINT16_MAX);
306         } else {
307             if (match->dl_vlan == htons(OFPVID11_ANY)) {
308                 /* Match any packet with a VLAN tag regardless of VID. */
309                 rule->flow.vlan_tci = htons(VLAN_CFI);
310                 rule->wc.vlan_tci_mask = htons(VLAN_CFI);
311             } else if (ntohs(match->dl_vlan) < 4096) {
312                 /* Match only packets with the specified VLAN VID. */
313                 rule->flow.vlan_tci = htons(VLAN_CFI) | match->dl_vlan;
314                 rule->wc.vlan_tci_mask = htons(VLAN_CFI | VLAN_VID_MASK);
315             } else {
316                 /* Invalid VID. */
317                 return OFPERR_OFPBMC_BAD_VALUE;
318             }
319
320             if (!(wc & OFPFW11_DL_VLAN_PCP)) {
321                 if (match->dl_vlan_pcp <= 7) {
322                     rule->flow.vlan_tci |= htons(match->dl_vlan_pcp
323                                                  << VLAN_PCP_SHIFT);
324                     rule->wc.vlan_tci_mask |= htons(VLAN_PCP_MASK);
325                 } else {
326                     /* Invalid PCP. */
327                     return OFPERR_OFPBMC_BAD_VALUE;
328                 }
329             }
330         }
331     }
332
333     if (!(wc & OFPFW11_DL_TYPE)) {
334         cls_rule_set_dl_type(rule,
335                              ofputil_dl_type_from_openflow(match->dl_type));
336     }
337
338     ipv4 = rule->flow.dl_type == htons(ETH_TYPE_IP);
339     arp = rule->flow.dl_type == htons(ETH_TYPE_ARP);
340
341     if (ipv4 && !(wc & OFPFW11_NW_TOS)) {
342         if (match->nw_tos & ~IP_DSCP_MASK) {
343             /* Invalid TOS. */
344             return OFPERR_OFPBMC_BAD_VALUE;
345         }
346
347         cls_rule_set_nw_dscp(rule, match->nw_tos);
348     }
349
350     if (ipv4 || arp) {
351         if (!(wc & OFPFW11_NW_PROTO)) {
352             cls_rule_set_nw_proto(rule, match->nw_proto);
353         }
354         cls_rule_set_nw_src_masked(rule, match->nw_src, ~match->nw_src_mask);
355         cls_rule_set_nw_dst_masked(rule, match->nw_dst, ~match->nw_dst_mask);
356     }
357
358 #define OFPFW11_TP_ALL (OFPFW11_TP_SRC | OFPFW11_TP_DST)
359     if (ipv4 && (wc & OFPFW11_TP_ALL) != OFPFW11_TP_ALL) {
360         switch (rule->flow.nw_proto) {
361         case IPPROTO_ICMP:
362             /* "A.2.3 Flow Match Structures" in OF1.1 says:
363              *
364              *    The tp_src and tp_dst fields will be ignored unless the
365              *    network protocol specified is as TCP, UDP or SCTP.
366              *
367              * but I'm pretty sure we should support ICMP too, otherwise
368              * that's a regression from OF1.0. */
369             if (!(wc & OFPFW11_TP_SRC)) {
370                 uint16_t icmp_type = ntohs(match->tp_src);
371                 if (icmp_type < 0x100) {
372                     cls_rule_set_icmp_type(rule, icmp_type);
373                 } else {
374                     return OFPERR_OFPBMC_BAD_FIELD;
375                 }
376             }
377             if (!(wc & OFPFW11_TP_DST)) {
378                 uint16_t icmp_code = ntohs(match->tp_dst);
379                 if (icmp_code < 0x100) {
380                     cls_rule_set_icmp_code(rule, icmp_code);
381                 } else {
382                     return OFPERR_OFPBMC_BAD_FIELD;
383                 }
384             }
385             break;
386
387         case IPPROTO_TCP:
388         case IPPROTO_UDP:
389             if (!(wc & (OFPFW11_TP_SRC))) {
390                 cls_rule_set_tp_src(rule, match->tp_src);
391             }
392             if (!(wc & (OFPFW11_TP_DST))) {
393                 cls_rule_set_tp_dst(rule, match->tp_dst);
394             }
395             break;
396
397         case IPPROTO_SCTP:
398             /* We don't support SCTP and it seems that we should tell the
399              * controller, since OF1.1 implementations are supposed to. */
400             return OFPERR_OFPBMC_BAD_FIELD;
401
402         default:
403             /* OF1.1 says explicitly to ignore this. */
404             break;
405         }
406     }
407
408     if (rule->flow.dl_type == htons(ETH_TYPE_MPLS) ||
409         rule->flow.dl_type == htons(ETH_TYPE_MPLS_MCAST)) {
410         enum { OFPFW11_MPLS_ALL = OFPFW11_MPLS_LABEL | OFPFW11_MPLS_TC };
411
412         if ((wc & OFPFW11_MPLS_ALL) != OFPFW11_MPLS_ALL) {
413             /* MPLS not supported. */
414             return OFPERR_OFPBMC_BAD_TAG;
415         }
416     }
417
418     if (match->metadata_mask != htonll(UINT64_MAX)) {
419         cls_rule_set_metadata_masked(rule, match->metadata,
420                                      ~match->metadata_mask);
421     }
422
423     return 0;
424 }
425
426 /* Convert 'rule' into the OpenFlow 1.1 match structure 'match'. */
427 void
428 ofputil_cls_rule_to_ofp11_match(const struct cls_rule *rule,
429                                 struct ofp11_match *match)
430 {
431     uint32_t wc = 0;
432     int i;
433
434     memset(match, 0, sizeof *match);
435     match->omh.type = htons(OFPMT_STANDARD);
436     match->omh.length = htons(OFPMT11_STANDARD_LENGTH);
437
438     if (rule->wc.wildcards & FWW_IN_PORT) {
439         wc |= OFPFW11_IN_PORT;
440     } else {
441         match->in_port = ofputil_port_to_ofp11(rule->flow.in_port);
442     }
443
444
445     memcpy(match->dl_src, rule->flow.dl_src, ETH_ADDR_LEN);
446     for (i = 0; i < ETH_ADDR_LEN; i++) {
447         match->dl_src_mask[i] = ~rule->wc.dl_src_mask[i];
448     }
449
450     memcpy(match->dl_dst, rule->flow.dl_dst, ETH_ADDR_LEN);
451     for (i = 0; i < ETH_ADDR_LEN; i++) {
452         match->dl_dst_mask[i] = ~rule->wc.dl_dst_mask[i];
453     }
454
455     if (rule->wc.vlan_tci_mask == htons(0)) {
456         wc |= OFPFW11_DL_VLAN | OFPFW11_DL_VLAN_PCP;
457     } else if (rule->wc.vlan_tci_mask & htons(VLAN_CFI)
458                && !(rule->flow.vlan_tci & htons(VLAN_CFI))) {
459         match->dl_vlan = htons(OFPVID11_NONE);
460         wc |= OFPFW11_DL_VLAN_PCP;
461     } else {
462         if (!(rule->wc.vlan_tci_mask & htons(VLAN_VID_MASK))) {
463             match->dl_vlan = htons(OFPVID11_ANY);
464         } else {
465             match->dl_vlan = htons(vlan_tci_to_vid(rule->flow.vlan_tci));
466         }
467
468         if (!(rule->wc.vlan_tci_mask & htons(VLAN_PCP_MASK))) {
469             wc |= OFPFW11_DL_VLAN_PCP;
470         } else {
471             match->dl_vlan_pcp = vlan_tci_to_pcp(rule->flow.vlan_tci);
472         }
473     }
474
475     if (rule->wc.wildcards & FWW_DL_TYPE) {
476         wc |= OFPFW11_DL_TYPE;
477     } else {
478         match->dl_type = ofputil_dl_type_to_openflow(rule->flow.dl_type);
479     }
480
481     if (rule->wc.wildcards & FWW_NW_DSCP) {
482         wc |= OFPFW11_NW_TOS;
483     } else {
484         match->nw_tos = rule->flow.nw_tos & IP_DSCP_MASK;
485     }
486
487     if (rule->wc.wildcards & FWW_NW_PROTO) {
488         wc |= OFPFW11_NW_PROTO;
489     } else {
490         match->nw_proto = rule->flow.nw_proto;
491     }
492
493     match->nw_src = rule->flow.nw_src;
494     match->nw_src_mask = ~rule->wc.nw_src_mask;
495     match->nw_dst = rule->flow.nw_dst;
496     match->nw_dst_mask = ~rule->wc.nw_dst_mask;
497
498     if (!rule->wc.tp_src_mask) {
499         wc |= OFPFW11_TP_SRC;
500     } else {
501         match->tp_src = rule->flow.tp_src;
502     }
503
504     if (!rule->wc.tp_dst_mask) {
505         wc |= OFPFW11_TP_DST;
506     } else {
507         match->tp_dst = rule->flow.tp_dst;
508     }
509
510     /* MPLS not supported. */
511     wc |= OFPFW11_MPLS_LABEL;
512     wc |= OFPFW11_MPLS_TC;
513
514     match->metadata = rule->flow.metadata;
515     match->metadata_mask = ~rule->wc.metadata_mask;
516
517     match->wildcards = htonl(wc);
518 }
519
520 /* Given a 'dl_type' value in the format used in struct flow, returns the
521  * corresponding 'dl_type' value for use in an ofp10_match or ofp11_match
522  * structure. */
523 ovs_be16
524 ofputil_dl_type_to_openflow(ovs_be16 flow_dl_type)
525 {
526     return (flow_dl_type == htons(FLOW_DL_TYPE_NONE)
527             ? htons(OFP_DL_TYPE_NOT_ETH_TYPE)
528             : flow_dl_type);
529 }
530
531 /* Given a 'dl_type' value in the format used in an ofp10_match or ofp11_match
532  * structure, returns the corresponding 'dl_type' value for use in struct
533  * flow. */
534 ovs_be16
535 ofputil_dl_type_from_openflow(ovs_be16 ofp_dl_type)
536 {
537     return (ofp_dl_type == htons(OFP_DL_TYPE_NOT_ETH_TYPE)
538             ? htons(FLOW_DL_TYPE_NONE)
539             : ofp_dl_type);
540 }
541
542 /* Returns a transaction ID to use for an outgoing OpenFlow message. */
543 static ovs_be32
544 alloc_xid(void)
545 {
546     static uint32_t next_xid = 1;
547     return htonl(next_xid++);
548 }
549 \f
550 /* Basic parsing of OpenFlow messages. */
551
552 struct ofputil_msg_type {
553     enum ofputil_msg_code code; /* OFPUTIL_*. */
554     uint8_t ofp_version;        /* An OpenFlow version or 0 for "any". */
555     uint32_t value;             /* OFPT_*, OFPST_*, NXT_*, or NXST_*. */
556     const char *name;           /* e.g. "OFPT_FLOW_REMOVED". */
557     unsigned int min_size;      /* Minimum total message size in bytes. */
558     /* 0 if 'min_size' is the exact size that the message must be.  Otherwise,
559      * the message may exceed 'min_size' by an even multiple of this value. */
560     unsigned int extra_multiple;
561 };
562
563 /* Represents a malformed OpenFlow message. */
564 static const struct ofputil_msg_type ofputil_invalid_type = {
565     OFPUTIL_MSG_INVALID, 0, 0, "OFPUTIL_MSG_INVALID", 0, 0
566 };
567
568 struct ofputil_msg_category {
569     const char *name;           /* e.g. "OpenFlow message" */
570     const struct ofputil_msg_type *types;
571     size_t n_types;
572     enum ofperr missing_error;  /* Error value for missing type. */
573 };
574
575 static enum ofperr
576 ofputil_check_length(const struct ofputil_msg_type *type, unsigned int size)
577 {
578     switch (type->extra_multiple) {
579     case 0:
580         if (size != type->min_size) {
581             VLOG_WARN_RL(&bad_ofmsg_rl, "received %s with incorrect "
582                          "length %u (expected length %u)",
583                          type->name, size, type->min_size);
584             return OFPERR_OFPBRC_BAD_LEN;
585         }
586         return 0;
587
588     case 1:
589         if (size < type->min_size) {
590             VLOG_WARN_RL(&bad_ofmsg_rl, "received %s with incorrect "
591                          "length %u (expected length at least %u bytes)",
592                          type->name, size, type->min_size);
593             return OFPERR_OFPBRC_BAD_LEN;
594         }
595         return 0;
596
597     default:
598         if (size < type->min_size
599             || (size - type->min_size) % type->extra_multiple) {
600             VLOG_WARN_RL(&bad_ofmsg_rl, "received %s with incorrect "
601                          "length %u (must be exactly %u bytes or longer "
602                          "by an integer multiple of %u bytes)",
603                          type->name, size,
604                          type->min_size, type->extra_multiple);
605             return OFPERR_OFPBRC_BAD_LEN;
606         }
607         return 0;
608     }
609 }
610
611 static enum ofperr
612 ofputil_lookup_openflow_message(const struct ofputil_msg_category *cat,
613                                 uint8_t version, uint32_t value,
614                                 const struct ofputil_msg_type **typep)
615 {
616     const struct ofputil_msg_type *type;
617
618     for (type = cat->types; type < &cat->types[cat->n_types]; type++) {
619         if (type->value == value
620             && (!type->ofp_version || version == type->ofp_version)) {
621             *typep = type;
622             return 0;
623         }
624     }
625
626     VLOG_WARN_RL(&bad_ofmsg_rl, "received %s of unknown type %"PRIu32,
627                  cat->name, value);
628     return cat->missing_error;
629 }
630
631 static enum ofperr
632 ofputil_decode_vendor(const struct ofp_header *oh, size_t length,
633                       const struct ofputil_msg_type **typep)
634 {
635     static const struct ofputil_msg_type nxt_messages[] = {
636         { OFPUTIL_NXT_ROLE_REQUEST, OFP10_VERSION,
637           NXT_ROLE_REQUEST, "NXT_ROLE_REQUEST",
638           sizeof(struct nx_role_request), 0 },
639
640         { OFPUTIL_NXT_ROLE_REPLY, OFP10_VERSION,
641           NXT_ROLE_REPLY, "NXT_ROLE_REPLY",
642           sizeof(struct nx_role_request), 0 },
643
644         { OFPUTIL_NXT_SET_FLOW_FORMAT, OFP10_VERSION,
645           NXT_SET_FLOW_FORMAT, "NXT_SET_FLOW_FORMAT",
646           sizeof(struct nx_set_flow_format), 0 },
647
648         { OFPUTIL_NXT_SET_PACKET_IN_FORMAT, OFP10_VERSION,
649           NXT_SET_PACKET_IN_FORMAT, "NXT_SET_PACKET_IN_FORMAT",
650           sizeof(struct nx_set_packet_in_format), 0 },
651
652         { OFPUTIL_NXT_PACKET_IN, OFP10_VERSION,
653           NXT_PACKET_IN, "NXT_PACKET_IN",
654           sizeof(struct nx_packet_in), 1 },
655
656         { OFPUTIL_NXT_FLOW_MOD, OFP10_VERSION,
657           NXT_FLOW_MOD, "NXT_FLOW_MOD",
658           sizeof(struct nx_flow_mod), 8 },
659
660         { OFPUTIL_NXT_FLOW_REMOVED, OFP10_VERSION,
661           NXT_FLOW_REMOVED, "NXT_FLOW_REMOVED",
662           sizeof(struct nx_flow_removed), 8 },
663
664         { OFPUTIL_NXT_FLOW_MOD_TABLE_ID, OFP10_VERSION,
665           NXT_FLOW_MOD_TABLE_ID, "NXT_FLOW_MOD_TABLE_ID",
666           sizeof(struct nx_flow_mod_table_id), 0 },
667
668         { OFPUTIL_NXT_FLOW_AGE, OFP10_VERSION,
669           NXT_FLOW_AGE, "NXT_FLOW_AGE",
670           sizeof(struct nicira_header), 0 },
671
672         { OFPUTIL_NXT_SET_ASYNC_CONFIG, OFP10_VERSION,
673           NXT_SET_ASYNC_CONFIG, "NXT_SET_ASYNC_CONFIG",
674           sizeof(struct nx_async_config), 0 },
675
676         { OFPUTIL_NXT_SET_CONTROLLER_ID, OFP10_VERSION,
677           NXT_SET_CONTROLLER_ID, "NXT_SET_CONTROLLER_ID",
678           sizeof(struct nx_controller_id), 0 },
679     };
680
681     static const struct ofputil_msg_category nxt_category = {
682         "Nicira extension message",
683         nxt_messages, ARRAY_SIZE(nxt_messages),
684         OFPERR_OFPBRC_BAD_SUBTYPE
685     };
686
687     const struct ofp_vendor_header *ovh;
688     const struct nicira_header *nh;
689
690     if (length < sizeof(struct ofp_vendor_header)) {
691         if (length == ntohs(oh->length)) {
692             VLOG_WARN_RL(&bad_ofmsg_rl, "truncated vendor message");
693         }
694         return OFPERR_OFPBRC_BAD_LEN;
695     }
696
697     ovh = (const struct ofp_vendor_header *) oh;
698     if (ovh->vendor != htonl(NX_VENDOR_ID)) {
699         VLOG_WARN_RL(&bad_ofmsg_rl, "received vendor message for unknown "
700                      "vendor %"PRIx32, ntohl(ovh->vendor));
701         return OFPERR_OFPBRC_BAD_VENDOR;
702     }
703
704     if (length < sizeof(struct nicira_header)) {
705         if (length == ntohs(oh->length)) {
706             VLOG_WARN_RL(&bad_ofmsg_rl, "received Nicira vendor message of "
707                          "length %u (expected at least %zu)",
708                          ntohs(ovh->header.length),
709                          sizeof(struct nicira_header));
710         }
711         return OFPERR_OFPBRC_BAD_LEN;
712     }
713
714     nh = (const struct nicira_header *) oh;
715     return ofputil_lookup_openflow_message(&nxt_category, oh->version,
716                                            ntohl(nh->subtype), typep);
717 }
718
719 static enum ofperr
720 check_nxstats_msg(const struct ofp_header *oh, size_t length)
721 {
722     const struct ofp_stats_msg *osm = (const struct ofp_stats_msg *) oh;
723     ovs_be32 vendor;
724
725     if (length < sizeof(struct ofp_vendor_stats_msg)) {
726         if (length == ntohs(oh->length)) {
727             VLOG_WARN_RL(&bad_ofmsg_rl, "truncated vendor stats message");
728         }
729         return OFPERR_OFPBRC_BAD_LEN;
730     }
731
732     memcpy(&vendor, osm + 1, sizeof vendor);
733     if (vendor != htonl(NX_VENDOR_ID)) {
734         VLOG_WARN_RL(&bad_ofmsg_rl, "received vendor stats message for "
735                      "unknown vendor %"PRIx32, ntohl(vendor));
736         return OFPERR_OFPBRC_BAD_VENDOR;
737     }
738
739     if (length < sizeof(struct nicira_stats_msg)) {
740         if (length == ntohs(osm->header.length)) {
741             VLOG_WARN_RL(&bad_ofmsg_rl, "truncated Nicira stats message");
742         }
743         return OFPERR_OFPBRC_BAD_LEN;
744     }
745
746     return 0;
747 }
748
749 static enum ofperr
750 ofputil_decode_nxst_request(const struct ofp_header *oh, size_t length,
751                             const struct ofputil_msg_type **typep)
752 {
753     static const struct ofputil_msg_type nxst_requests[] = {
754         { OFPUTIL_NXST_FLOW_REQUEST, OFP10_VERSION,
755           NXST_FLOW, "NXST_FLOW request",
756           sizeof(struct nx_flow_stats_request), 8 },
757
758         { OFPUTIL_NXST_AGGREGATE_REQUEST, OFP10_VERSION,
759           NXST_AGGREGATE, "NXST_AGGREGATE request",
760           sizeof(struct nx_aggregate_stats_request), 8 },
761     };
762
763     static const struct ofputil_msg_category nxst_request_category = {
764         "Nicira extension statistics request",
765         nxst_requests, ARRAY_SIZE(nxst_requests),
766         OFPERR_OFPBRC_BAD_SUBTYPE
767     };
768
769     const struct nicira_stats_msg *nsm;
770     enum ofperr error;
771
772     error = check_nxstats_msg(oh, length);
773     if (error) {
774         return error;
775     }
776
777     nsm = (struct nicira_stats_msg *) oh;
778     return ofputil_lookup_openflow_message(&nxst_request_category, oh->version,
779                                            ntohl(nsm->subtype), typep);
780 }
781
782 static enum ofperr
783 ofputil_decode_nxst_reply(const struct ofp_header *oh, size_t length,
784                           const struct ofputil_msg_type **typep)
785 {
786     static const struct ofputil_msg_type nxst_replies[] = {
787         { OFPUTIL_NXST_FLOW_REPLY, OFP10_VERSION,
788           NXST_FLOW, "NXST_FLOW reply",
789           sizeof(struct nicira_stats_msg), 8 },
790
791         { OFPUTIL_NXST_AGGREGATE_REPLY, OFP10_VERSION,
792           NXST_AGGREGATE, "NXST_AGGREGATE reply",
793           sizeof(struct nx_aggregate_stats_reply), 0 },
794     };
795
796     static const struct ofputil_msg_category nxst_reply_category = {
797         "Nicira extension statistics reply",
798         nxst_replies, ARRAY_SIZE(nxst_replies),
799         OFPERR_OFPBRC_BAD_SUBTYPE
800     };
801
802     const struct nicira_stats_msg *nsm;
803     enum ofperr error;
804
805     error = check_nxstats_msg(oh, length);
806     if (error) {
807         return error;
808     }
809
810     nsm = (struct nicira_stats_msg *) oh;
811     return ofputil_lookup_openflow_message(&nxst_reply_category, oh->version,
812                                            ntohl(nsm->subtype), typep);
813 }
814
815 static enum ofperr
816 check_stats_msg(const struct ofp_header *oh, size_t length)
817 {
818     if (length < sizeof(struct ofp_stats_msg)) {
819         if (length == ntohs(oh->length)) {
820             VLOG_WARN_RL(&bad_ofmsg_rl, "truncated stats message");
821         }
822         return OFPERR_OFPBRC_BAD_LEN;
823     }
824
825     return 0;
826 }
827
828 static enum ofperr
829 ofputil_decode_ofpst_request(const struct ofp_header *oh, size_t length,
830                              const struct ofputil_msg_type **typep)
831 {
832     static const struct ofputil_msg_type ofpst_requests[] = {
833         { OFPUTIL_OFPST_DESC_REQUEST, OFP10_VERSION,
834           OFPST_DESC, "OFPST_DESC request",
835           sizeof(struct ofp_stats_msg), 0 },
836
837         { OFPUTIL_OFPST_FLOW_REQUEST, OFP10_VERSION,
838           OFPST_FLOW, "OFPST_FLOW request",
839           sizeof(struct ofp_flow_stats_request), 0 },
840
841         { OFPUTIL_OFPST_AGGREGATE_REQUEST, OFP10_VERSION,
842           OFPST_AGGREGATE, "OFPST_AGGREGATE request",
843           sizeof(struct ofp_flow_stats_request), 0 },
844
845         { OFPUTIL_OFPST_TABLE_REQUEST, OFP10_VERSION,
846           OFPST_TABLE, "OFPST_TABLE request",
847           sizeof(struct ofp_stats_msg), 0 },
848
849         { OFPUTIL_OFPST_PORT_REQUEST, OFP10_VERSION,
850           OFPST_PORT, "OFPST_PORT request",
851           sizeof(struct ofp_port_stats_request), 0 },
852
853         { OFPUTIL_OFPST_QUEUE_REQUEST, OFP10_VERSION,
854           OFPST_QUEUE, "OFPST_QUEUE request",
855           sizeof(struct ofp_queue_stats_request), 0 },
856
857         { OFPUTIL_OFPST_PORT_DESC_REQUEST, OFP10_VERSION,
858           OFPST_PORT_DESC, "OFPST_PORT_DESC request",
859           sizeof(struct ofp_stats_msg), 0 },
860
861         { 0, 0,
862           OFPST_VENDOR, "OFPST_VENDOR request",
863           sizeof(struct ofp_vendor_stats_msg), 1 },
864     };
865
866     static const struct ofputil_msg_category ofpst_request_category = {
867         "OpenFlow statistics",
868         ofpst_requests, ARRAY_SIZE(ofpst_requests),
869         OFPERR_OFPBRC_BAD_STAT
870     };
871
872     const struct ofp_stats_msg *request = (const struct ofp_stats_msg *) oh;
873     enum ofperr error;
874
875     error = check_stats_msg(oh, length);
876     if (error) {
877         return error;
878     }
879
880     error = ofputil_lookup_openflow_message(&ofpst_request_category,
881                                             oh->version, ntohs(request->type),
882                                             typep);
883     if (!error && request->type == htons(OFPST_VENDOR)) {
884         error = ofputil_decode_nxst_request(oh, length, typep);
885     }
886     return error;
887 }
888
889 static enum ofperr
890 ofputil_decode_ofpst_reply(const struct ofp_header *oh, size_t length,
891                            const struct ofputil_msg_type **typep)
892 {
893     static const struct ofputil_msg_type ofpst_replies[] = {
894         { OFPUTIL_OFPST_DESC_REPLY, OFP10_VERSION,
895           OFPST_DESC, "OFPST_DESC reply",
896           sizeof(struct ofp_desc_stats), 0 },
897
898         { OFPUTIL_OFPST_FLOW_REPLY, OFP10_VERSION,
899           OFPST_FLOW, "OFPST_FLOW reply",
900           sizeof(struct ofp_stats_msg), 1 },
901
902         { OFPUTIL_OFPST_AGGREGATE_REPLY, OFP10_VERSION,
903           OFPST_AGGREGATE, "OFPST_AGGREGATE reply",
904           sizeof(struct ofp_aggregate_stats_reply), 0 },
905
906         { OFPUTIL_OFPST_TABLE_REPLY, OFP10_VERSION,
907           OFPST_TABLE, "OFPST_TABLE reply",
908           sizeof(struct ofp_stats_msg), sizeof(struct ofp_table_stats) },
909
910         { OFPUTIL_OFPST_PORT_REPLY, OFP10_VERSION,
911           OFPST_PORT, "OFPST_PORT reply",
912           sizeof(struct ofp_stats_msg), sizeof(struct ofp_port_stats) },
913
914         { OFPUTIL_OFPST_QUEUE_REPLY, OFP10_VERSION,
915           OFPST_QUEUE, "OFPST_QUEUE reply",
916           sizeof(struct ofp_stats_msg), sizeof(struct ofp_queue_stats) },
917
918         { OFPUTIL_OFPST_PORT_DESC_REPLY, OFP10_VERSION,
919           OFPST_PORT_DESC, "OFPST_PORT_DESC reply",
920           sizeof(struct ofp_stats_msg), sizeof(struct ofp10_phy_port) },
921
922         { 0, 0,
923           OFPST_VENDOR, "OFPST_VENDOR reply",
924           sizeof(struct ofp_vendor_stats_msg), 1 },
925     };
926
927     static const struct ofputil_msg_category ofpst_reply_category = {
928         "OpenFlow statistics",
929         ofpst_replies, ARRAY_SIZE(ofpst_replies),
930         OFPERR_OFPBRC_BAD_STAT
931     };
932
933     const struct ofp_stats_msg *reply = (const struct ofp_stats_msg *) oh;
934     enum ofperr error;
935
936     error = check_stats_msg(oh, length);
937     if (error) {
938         return error;
939     }
940
941     error = ofputil_lookup_openflow_message(&ofpst_reply_category, oh->version,
942                                            ntohs(reply->type), typep);
943     if (!error && reply->type == htons(OFPST_VENDOR)) {
944         error = ofputil_decode_nxst_reply(oh, length, typep);
945     }
946     return error;
947 }
948
949 static enum ofperr
950 ofputil_decode_msg_type__(const struct ofp_header *oh, size_t length,
951                           const struct ofputil_msg_type **typep)
952 {
953     static const struct ofputil_msg_type ofpt_messages[] = {
954         { OFPUTIL_OFPT_HELLO, OFP10_VERSION,
955           OFPT_HELLO, "OFPT_HELLO",
956           sizeof(struct ofp_hello), 1 },
957
958         { OFPUTIL_OFPT_ERROR, 0,
959           OFPT_ERROR, "OFPT_ERROR",
960           sizeof(struct ofp_error_msg), 1 },
961
962         { OFPUTIL_OFPT_ECHO_REQUEST, OFP10_VERSION,
963           OFPT_ECHO_REQUEST, "OFPT_ECHO_REQUEST",
964           sizeof(struct ofp_header), 1 },
965
966         { OFPUTIL_OFPT_ECHO_REPLY, OFP10_VERSION,
967           OFPT_ECHO_REPLY, "OFPT_ECHO_REPLY",
968           sizeof(struct ofp_header), 1 },
969
970         { OFPUTIL_OFPT_FEATURES_REQUEST, OFP10_VERSION,
971           OFPT_FEATURES_REQUEST, "OFPT_FEATURES_REQUEST",
972           sizeof(struct ofp_header), 0 },
973
974         { OFPUTIL_OFPT_FEATURES_REPLY, OFP10_VERSION,
975           OFPT_FEATURES_REPLY, "OFPT_FEATURES_REPLY",
976           sizeof(struct ofp_switch_features), sizeof(struct ofp10_phy_port) },
977         { OFPUTIL_OFPT_FEATURES_REPLY, OFP11_VERSION,
978           OFPT_FEATURES_REPLY, "OFPT_FEATURES_REPLY",
979           sizeof(struct ofp_switch_features), sizeof(struct ofp11_port) },
980
981         { OFPUTIL_OFPT_GET_CONFIG_REQUEST, OFP10_VERSION,
982           OFPT_GET_CONFIG_REQUEST, "OFPT_GET_CONFIG_REQUEST",
983           sizeof(struct ofp_header), 0 },
984
985         { OFPUTIL_OFPT_GET_CONFIG_REPLY, OFP10_VERSION,
986           OFPT_GET_CONFIG_REPLY, "OFPT_GET_CONFIG_REPLY",
987           sizeof(struct ofp_switch_config), 0 },
988
989         { OFPUTIL_OFPT_SET_CONFIG, OFP10_VERSION,
990           OFPT_SET_CONFIG, "OFPT_SET_CONFIG",
991           sizeof(struct ofp_switch_config), 0 },
992
993         { OFPUTIL_OFPT_PACKET_IN, OFP10_VERSION,
994           OFPT_PACKET_IN, "OFPT_PACKET_IN",
995           offsetof(struct ofp_packet_in, data), 1 },
996
997         { OFPUTIL_OFPT_FLOW_REMOVED, OFP10_VERSION,
998           OFPT_FLOW_REMOVED, "OFPT_FLOW_REMOVED",
999           sizeof(struct ofp_flow_removed), 0 },
1000
1001         { OFPUTIL_OFPT_PORT_STATUS, OFP10_VERSION,
1002           OFPT_PORT_STATUS, "OFPT_PORT_STATUS",
1003           sizeof(struct ofp_port_status) + sizeof(struct ofp10_phy_port), 0 },
1004         { OFPUTIL_OFPT_PORT_STATUS, OFP11_VERSION,
1005           OFPT_PORT_STATUS, "OFPT_PORT_STATUS",
1006           sizeof(struct ofp_port_status) + sizeof(struct ofp11_port), 0 },
1007
1008         { OFPUTIL_OFPT_PACKET_OUT, OFP10_VERSION,
1009           OFPT_PACKET_OUT, "OFPT_PACKET_OUT",
1010           sizeof(struct ofp_packet_out), 1 },
1011
1012         { OFPUTIL_OFPT_FLOW_MOD, OFP10_VERSION,
1013           OFPT_FLOW_MOD, "OFPT_FLOW_MOD",
1014           sizeof(struct ofp_flow_mod), 1 },
1015
1016         { OFPUTIL_OFPT_PORT_MOD, OFP10_VERSION,
1017           OFPT10_PORT_MOD, "OFPT_PORT_MOD",
1018           sizeof(struct ofp10_port_mod), 0 },
1019         { OFPUTIL_OFPT_PORT_MOD, OFP11_VERSION,
1020           OFPT11_PORT_MOD, "OFPT_PORT_MOD",
1021           sizeof(struct ofp11_port_mod), 0 },
1022
1023         { 0, OFP10_VERSION,
1024           OFPT10_STATS_REQUEST, "OFPT_STATS_REQUEST",
1025           sizeof(struct ofp_stats_msg), 1 },
1026
1027         { 0, OFP10_VERSION,
1028           OFPT10_STATS_REPLY, "OFPT_STATS_REPLY",
1029           sizeof(struct ofp_stats_msg), 1 },
1030
1031         { OFPUTIL_OFPT_BARRIER_REQUEST, OFP10_VERSION,
1032           OFPT10_BARRIER_REQUEST, "OFPT_BARRIER_REQUEST",
1033           sizeof(struct ofp_header), 0 },
1034
1035         { OFPUTIL_OFPT_BARRIER_REPLY, OFP10_VERSION,
1036           OFPT10_BARRIER_REPLY, "OFPT_BARRIER_REPLY",
1037           sizeof(struct ofp_header), 0 },
1038
1039         { 0, 0,
1040           OFPT_VENDOR, "OFPT_VENDOR",
1041           sizeof(struct ofp_vendor_header), 1 },
1042     };
1043
1044     static const struct ofputil_msg_category ofpt_category = {
1045         "OpenFlow message",
1046         ofpt_messages, ARRAY_SIZE(ofpt_messages),
1047         OFPERR_OFPBRC_BAD_TYPE
1048     };
1049
1050     enum ofperr error;
1051
1052     error = ofputil_lookup_openflow_message(&ofpt_category, oh->version,
1053                                             oh->type, typep);
1054     if (!error) {
1055         switch ((oh->version << 8) | oh->type) {
1056         case (OFP10_VERSION << 8) | OFPT_VENDOR:
1057         case (OFP11_VERSION << 8) | OFPT_VENDOR:
1058             error = ofputil_decode_vendor(oh, length, typep);
1059             break;
1060
1061         case (OFP10_VERSION << 8) | OFPT10_STATS_REQUEST:
1062         case (OFP11_VERSION << 8) | OFPT11_STATS_REQUEST:
1063             error = ofputil_decode_ofpst_request(oh, length, typep);
1064             break;
1065
1066         case (OFP10_VERSION << 8) | OFPT10_STATS_REPLY:
1067         case (OFP11_VERSION << 8) | OFPT11_STATS_REPLY:
1068             error = ofputil_decode_ofpst_reply(oh, length, typep);
1069
1070         default:
1071             break;
1072         }
1073     }
1074     return error;
1075 }
1076
1077 /* Decodes the message type represented by 'oh'.  Returns 0 if successful or an
1078  * OpenFlow error code on failure.  Either way, stores in '*typep' a type
1079  * structure that can be inspected with the ofputil_msg_type_*() functions.
1080  *
1081  * oh->length must indicate the correct length of the message (and must be at
1082  * least sizeof(struct ofp_header)).
1083  *
1084  * Success indicates that 'oh' is at least as long as the minimum-length
1085  * message of its type. */
1086 enum ofperr
1087 ofputil_decode_msg_type(const struct ofp_header *oh,
1088                         const struct ofputil_msg_type **typep)
1089 {
1090     size_t length = ntohs(oh->length);
1091     enum ofperr error;
1092
1093     error = ofputil_decode_msg_type__(oh, length, typep);
1094     if (!error) {
1095         error = ofputil_check_length(*typep, length);
1096     }
1097     if (error) {
1098         *typep = &ofputil_invalid_type;
1099     }
1100     return error;
1101 }
1102
1103 /* Decodes the message type represented by 'oh', of which only the first
1104  * 'length' bytes are available.  Returns 0 if successful or an OpenFlow error
1105  * code on failure.  Either way, stores in '*typep' a type structure that can
1106  * be inspected with the ofputil_msg_type_*() functions.  */
1107 enum ofperr
1108 ofputil_decode_msg_type_partial(const struct ofp_header *oh, size_t length,
1109                                 const struct ofputil_msg_type **typep)
1110 {
1111     enum ofperr error;
1112
1113     error = (length >= sizeof *oh
1114              ? ofputil_decode_msg_type__(oh, length, typep)
1115              : OFPERR_OFPBRC_BAD_LEN);
1116     if (error) {
1117         *typep = &ofputil_invalid_type;
1118     }
1119     return error;
1120 }
1121
1122 /* Returns an OFPUTIL_* message type code for 'type'. */
1123 enum ofputil_msg_code
1124 ofputil_msg_type_code(const struct ofputil_msg_type *type)
1125 {
1126     return type->code;
1127 }
1128 \f
1129 /* Protocols. */
1130
1131 struct proto_abbrev {
1132     enum ofputil_protocol protocol;
1133     const char *name;
1134 };
1135
1136 /* Most users really don't care about some of the differences between
1137  * protocols.  These abbreviations help with that. */
1138 static const struct proto_abbrev proto_abbrevs[] = {
1139     { OFPUTIL_P_ANY,      "any" },
1140     { OFPUTIL_P_OF10_ANY, "OpenFlow10" },
1141     { OFPUTIL_P_NXM_ANY,  "NXM" },
1142 };
1143 #define N_PROTO_ABBREVS ARRAY_SIZE(proto_abbrevs)
1144
1145 enum ofputil_protocol ofputil_flow_dump_protocols[] = {
1146     OFPUTIL_P_NXM,
1147     OFPUTIL_P_OF10,
1148 };
1149 size_t ofputil_n_flow_dump_protocols = ARRAY_SIZE(ofputil_flow_dump_protocols);
1150
1151 /* Returns the ofputil_protocol that is initially in effect on an OpenFlow
1152  * connection that has negotiated the given 'version'.  'version' should
1153  * normally be an 8-bit OpenFlow version identifier (e.g. 0x01 for OpenFlow
1154  * 1.0, 0x02 for OpenFlow 1.1).  Returns 0 if 'version' is not supported or
1155  * outside the valid range.  */
1156 enum ofputil_protocol
1157 ofputil_protocol_from_ofp_version(int version)
1158 {
1159     switch (version) {
1160     case OFP10_VERSION: return OFPUTIL_P_OF10;
1161     default: return 0;
1162     }
1163 }
1164
1165 /* Returns the OpenFlow protocol version number (e.g. OFP10_VERSION or
1166  * OFP11_VERSION) that corresponds to 'protocol'. */
1167 uint8_t
1168 ofputil_protocol_to_ofp_version(enum ofputil_protocol protocol)
1169 {
1170     switch (protocol) {
1171     case OFPUTIL_P_OF10:
1172     case OFPUTIL_P_OF10_TID:
1173     case OFPUTIL_P_NXM:
1174     case OFPUTIL_P_NXM_TID:
1175         return OFP10_VERSION;
1176     }
1177
1178     NOT_REACHED();
1179 }
1180
1181 /* Returns true if 'protocol' is a single OFPUTIL_P_* value, false
1182  * otherwise. */
1183 bool
1184 ofputil_protocol_is_valid(enum ofputil_protocol protocol)
1185 {
1186     return protocol & OFPUTIL_P_ANY && is_pow2(protocol);
1187 }
1188
1189 /* Returns the equivalent of 'protocol' with the Nicira flow_mod_table_id
1190  * extension turned on or off if 'enable' is true or false, respectively.
1191  *
1192  * This extension is only useful for protocols whose "standard" version does
1193  * not allow specific tables to be modified.  In particular, this is true of
1194  * OpenFlow 1.0.  In later versions of OpenFlow, a flow_mod request always
1195  * specifies a table ID and so there is no need for such an extension.  When
1196  * 'protocol' is such a protocol that doesn't need a flow_mod_table_id
1197  * extension, this function just returns its 'protocol' argument unchanged
1198  * regardless of the value of 'enable'.  */
1199 enum ofputil_protocol
1200 ofputil_protocol_set_tid(enum ofputil_protocol protocol, bool enable)
1201 {
1202     switch (protocol) {
1203     case OFPUTIL_P_OF10:
1204     case OFPUTIL_P_OF10_TID:
1205         return enable ? OFPUTIL_P_OF10_TID : OFPUTIL_P_OF10;
1206
1207     case OFPUTIL_P_NXM:
1208     case OFPUTIL_P_NXM_TID:
1209         return enable ? OFPUTIL_P_NXM_TID : OFPUTIL_P_NXM;
1210
1211     default:
1212         NOT_REACHED();
1213     }
1214 }
1215
1216 /* Returns the "base" version of 'protocol'.  That is, if 'protocol' includes
1217  * some extension to a standard protocol version, the return value is the
1218  * standard version of that protocol without any extension.  If 'protocol' is a
1219  * standard protocol version, returns 'protocol' unchanged. */
1220 enum ofputil_protocol
1221 ofputil_protocol_to_base(enum ofputil_protocol protocol)
1222 {
1223     return ofputil_protocol_set_tid(protocol, false);
1224 }
1225
1226 /* Returns 'new_base' with any extensions taken from 'cur'. */
1227 enum ofputil_protocol
1228 ofputil_protocol_set_base(enum ofputil_protocol cur,
1229                           enum ofputil_protocol new_base)
1230 {
1231     bool tid = (cur & OFPUTIL_P_TID) != 0;
1232
1233     switch (new_base) {
1234     case OFPUTIL_P_OF10:
1235     case OFPUTIL_P_OF10_TID:
1236         return ofputil_protocol_set_tid(OFPUTIL_P_OF10, tid);
1237
1238     case OFPUTIL_P_NXM:
1239     case OFPUTIL_P_NXM_TID:
1240         return ofputil_protocol_set_tid(OFPUTIL_P_NXM, tid);
1241
1242     default:
1243         NOT_REACHED();
1244     }
1245 }
1246
1247 /* Returns a string form of 'protocol', if a simple form exists (that is, if
1248  * 'protocol' is either a single protocol or it is a combination of protocols
1249  * that have a single abbreviation).  Otherwise, returns NULL. */
1250 const char *
1251 ofputil_protocol_to_string(enum ofputil_protocol protocol)
1252 {
1253     const struct proto_abbrev *p;
1254
1255     /* Use a "switch" statement for single-bit names so that we get a compiler
1256      * warning if we forget any. */
1257     switch (protocol) {
1258     case OFPUTIL_P_NXM:
1259         return "NXM-table_id";
1260
1261     case OFPUTIL_P_NXM_TID:
1262         return "NXM+table_id";
1263
1264     case OFPUTIL_P_OF10:
1265         return "OpenFlow10-table_id";
1266
1267     case OFPUTIL_P_OF10_TID:
1268         return "OpenFlow10+table_id";
1269     }
1270
1271     /* Check abbreviations. */
1272     for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
1273         if (protocol == p->protocol) {
1274             return p->name;
1275         }
1276     }
1277
1278     return NULL;
1279 }
1280
1281 /* Returns a string that represents 'protocols'.  The return value might be a
1282  * comma-separated list if 'protocols' doesn't have a simple name.  The return
1283  * value is "none" if 'protocols' is 0.
1284  *
1285  * The caller must free the returned string (with free()). */
1286 char *
1287 ofputil_protocols_to_string(enum ofputil_protocol protocols)
1288 {
1289     struct ds s;
1290
1291     assert(!(protocols & ~OFPUTIL_P_ANY));
1292     if (protocols == 0) {
1293         return xstrdup("none");
1294     }
1295
1296     ds_init(&s);
1297     while (protocols) {
1298         const struct proto_abbrev *p;
1299         int i;
1300
1301         if (s.length) {
1302             ds_put_char(&s, ',');
1303         }
1304
1305         for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
1306             if ((protocols & p->protocol) == p->protocol) {
1307                 ds_put_cstr(&s, p->name);
1308                 protocols &= ~p->protocol;
1309                 goto match;
1310             }
1311         }
1312
1313         for (i = 0; i < CHAR_BIT * sizeof(enum ofputil_protocol); i++) {
1314             enum ofputil_protocol bit = 1u << i;
1315
1316             if (protocols & bit) {
1317                 ds_put_cstr(&s, ofputil_protocol_to_string(bit));
1318                 protocols &= ~bit;
1319                 goto match;
1320             }
1321         }
1322         NOT_REACHED();
1323
1324     match: ;
1325     }
1326     return ds_steal_cstr(&s);
1327 }
1328
1329 static enum ofputil_protocol
1330 ofputil_protocol_from_string__(const char *s, size_t n)
1331 {
1332     const struct proto_abbrev *p;
1333     int i;
1334
1335     for (i = 0; i < CHAR_BIT * sizeof(enum ofputil_protocol); i++) {
1336         enum ofputil_protocol bit = 1u << i;
1337         const char *name = ofputil_protocol_to_string(bit);
1338
1339         if (name && n == strlen(name) && !strncasecmp(s, name, n)) {
1340             return bit;
1341         }
1342     }
1343
1344     for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
1345         if (n == strlen(p->name) && !strncasecmp(s, p->name, n)) {
1346             return p->protocol;
1347         }
1348     }
1349
1350     return 0;
1351 }
1352
1353 /* Returns the nonempty set of protocols represented by 's', which can be a
1354  * single protocol name or abbreviation or a comma-separated list of them.
1355  *
1356  * Aborts the program with an error message if 's' is invalid. */
1357 enum ofputil_protocol
1358 ofputil_protocols_from_string(const char *s)
1359 {
1360     const char *orig_s = s;
1361     enum ofputil_protocol protocols;
1362
1363     protocols = 0;
1364     while (*s) {
1365         enum ofputil_protocol p;
1366         size_t n;
1367
1368         n = strcspn(s, ",");
1369         if (n == 0) {
1370             s++;
1371             continue;
1372         }
1373
1374         p = ofputil_protocol_from_string__(s, n);
1375         if (!p) {
1376             ovs_fatal(0, "%.*s: unknown flow protocol", (int) n, s);
1377         }
1378         protocols |= p;
1379
1380         s += n;
1381     }
1382
1383     if (!protocols) {
1384         ovs_fatal(0, "%s: no flow protocol specified", orig_s);
1385     }
1386     return protocols;
1387 }
1388
1389 bool
1390 ofputil_packet_in_format_is_valid(enum nx_packet_in_format packet_in_format)
1391 {
1392     switch (packet_in_format) {
1393     case NXPIF_OPENFLOW10:
1394     case NXPIF_NXM:
1395         return true;
1396     }
1397
1398     return false;
1399 }
1400
1401 const char *
1402 ofputil_packet_in_format_to_string(enum nx_packet_in_format packet_in_format)
1403 {
1404     switch (packet_in_format) {
1405     case NXPIF_OPENFLOW10:
1406         return "openflow10";
1407     case NXPIF_NXM:
1408         return "nxm";
1409     default:
1410         NOT_REACHED();
1411     }
1412 }
1413
1414 int
1415 ofputil_packet_in_format_from_string(const char *s)
1416 {
1417     return (!strcmp(s, "openflow10") ? NXPIF_OPENFLOW10
1418             : !strcmp(s, "nxm") ? NXPIF_NXM
1419             : -1);
1420 }
1421
1422 static bool
1423 regs_fully_wildcarded(const struct flow_wildcards *wc)
1424 {
1425     int i;
1426
1427     for (i = 0; i < FLOW_N_REGS; i++) {
1428         if (wc->reg_masks[i] != 0) {
1429             return false;
1430         }
1431     }
1432     return true;
1433 }
1434
1435 /* Returns a bit-mask of ofputil_protocols that can be used for sending 'rule'
1436  * to a switch (e.g. to add or remove a flow).  Only NXM can handle tunnel IDs,
1437  * registers, or fixing the Ethernet multicast bit.  Otherwise, it's better to
1438  * use OpenFlow 1.0 protocol for backward compatibility. */
1439 enum ofputil_protocol
1440 ofputil_usable_protocols(const struct cls_rule *rule)
1441 {
1442     const struct flow_wildcards *wc = &rule->wc;
1443
1444     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 12);
1445
1446     /* NXM and OF1.1+ supports bitwise matching on ethernet addresses. */
1447     if (!eth_mask_is_exact(wc->dl_src_mask)
1448         && !eth_addr_is_zero(wc->dl_src_mask)) {
1449         return OFPUTIL_P_NXM_ANY;
1450     }
1451     if (!eth_mask_is_exact(wc->dl_dst_mask)
1452         && !eth_addr_is_zero(wc->dl_dst_mask)) {
1453         return OFPUTIL_P_NXM_ANY;
1454     }
1455
1456     /* NXM and OF1.1+ support matching metadata. */
1457     if (wc->metadata_mask != htonll(0)) {
1458         return OFPUTIL_P_NXM_ANY;
1459     }
1460
1461     /* Only NXM supports matching ARP hardware addresses. */
1462     if (!(wc->wildcards & FWW_ARP_SHA) || !(wc->wildcards & FWW_ARP_THA)) {
1463         return OFPUTIL_P_NXM_ANY;
1464     }
1465
1466     /* Only NXM supports matching IPv6 traffic. */
1467     if (!(wc->wildcards & FWW_DL_TYPE)
1468             && (rule->flow.dl_type == htons(ETH_TYPE_IPV6))) {
1469         return OFPUTIL_P_NXM_ANY;
1470     }
1471
1472     /* Only NXM supports matching registers. */
1473     if (!regs_fully_wildcarded(wc)) {
1474         return OFPUTIL_P_NXM_ANY;
1475     }
1476
1477     /* Only NXM supports matching tun_id. */
1478     if (wc->tun_id_mask != htonll(0)) {
1479         return OFPUTIL_P_NXM_ANY;
1480     }
1481
1482     /* Only NXM supports matching fragments. */
1483     if (wc->nw_frag_mask) {
1484         return OFPUTIL_P_NXM_ANY;
1485     }
1486
1487     /* Only NXM supports matching IPv6 flow label. */
1488     if (!(wc->wildcards & FWW_IPV6_LABEL)) {
1489         return OFPUTIL_P_NXM_ANY;
1490     }
1491
1492     /* Only NXM supports matching IP ECN bits. */
1493     if (!(wc->wildcards & FWW_NW_ECN)) {
1494         return OFPUTIL_P_NXM_ANY;
1495     }
1496
1497     /* Only NXM supports matching IP TTL/hop limit. */
1498     if (!(wc->wildcards & FWW_NW_TTL)) {
1499         return OFPUTIL_P_NXM_ANY;
1500     }
1501
1502     /* Only NXM supports non-CIDR IPv4 address masks. */
1503     if (!ip_is_cidr(wc->nw_src_mask) || !ip_is_cidr(wc->nw_dst_mask)) {
1504         return OFPUTIL_P_NXM_ANY;
1505     }
1506
1507     /* Only NXM supports bitwise matching on transport port. */
1508     if ((wc->tp_src_mask && wc->tp_src_mask != htons(UINT16_MAX)) ||
1509         (wc->tp_dst_mask && wc->tp_dst_mask != htons(UINT16_MAX))) {
1510         return OFPUTIL_P_NXM_ANY;
1511     }
1512
1513     /* Other formats can express this rule. */
1514     return OFPUTIL_P_ANY;
1515 }
1516
1517 /* Returns an OpenFlow message that, sent on an OpenFlow connection whose
1518  * protocol is 'current', at least partly transitions the protocol to 'want'.
1519  * Stores in '*next' the protocol that will be in effect on the OpenFlow
1520  * connection if the switch processes the returned message correctly.  (If
1521  * '*next != want' then the caller will have to iterate.)
1522  *
1523  * If 'current == want', returns NULL and stores 'current' in '*next'. */
1524 struct ofpbuf *
1525 ofputil_encode_set_protocol(enum ofputil_protocol current,
1526                             enum ofputil_protocol want,
1527                             enum ofputil_protocol *next)
1528 {
1529     enum ofputil_protocol cur_base, want_base;
1530     bool cur_tid, want_tid;
1531
1532     cur_base = ofputil_protocol_to_base(current);
1533     want_base = ofputil_protocol_to_base(want);
1534     if (cur_base != want_base) {
1535         *next = ofputil_protocol_set_base(current, want_base);
1536
1537         switch (want_base) {
1538         case OFPUTIL_P_NXM:
1539             return ofputil_encode_nx_set_flow_format(NXFF_NXM);
1540
1541         case OFPUTIL_P_OF10:
1542             return ofputil_encode_nx_set_flow_format(NXFF_OPENFLOW10);
1543
1544         case OFPUTIL_P_OF10_TID:
1545         case OFPUTIL_P_NXM_TID:
1546             NOT_REACHED();
1547         }
1548     }
1549
1550     cur_tid = (current & OFPUTIL_P_TID) != 0;
1551     want_tid = (want & OFPUTIL_P_TID) != 0;
1552     if (cur_tid != want_tid) {
1553         *next = ofputil_protocol_set_tid(current, want_tid);
1554         return ofputil_make_flow_mod_table_id(want_tid);
1555     }
1556
1557     assert(current == want);
1558
1559     *next = current;
1560     return NULL;
1561 }
1562
1563 /* Returns an NXT_SET_FLOW_FORMAT message that can be used to set the flow
1564  * format to 'nxff'.  */
1565 struct ofpbuf *
1566 ofputil_encode_nx_set_flow_format(enum nx_flow_format nxff)
1567 {
1568     struct nx_set_flow_format *sff;
1569     struct ofpbuf *msg;
1570
1571     assert(ofputil_nx_flow_format_is_valid(nxff));
1572
1573     sff = make_nxmsg(sizeof *sff, NXT_SET_FLOW_FORMAT, &msg);
1574     sff->format = htonl(nxff);
1575
1576     return msg;
1577 }
1578
1579 /* Returns the base protocol if 'flow_format' is a valid NXFF_* value, false
1580  * otherwise. */
1581 enum ofputil_protocol
1582 ofputil_nx_flow_format_to_protocol(enum nx_flow_format flow_format)
1583 {
1584     switch (flow_format) {
1585     case NXFF_OPENFLOW10:
1586         return OFPUTIL_P_OF10;
1587
1588     case NXFF_NXM:
1589         return OFPUTIL_P_NXM;
1590
1591     default:
1592         return 0;
1593     }
1594 }
1595
1596 /* Returns true if 'flow_format' is a valid NXFF_* value, false otherwise. */
1597 bool
1598 ofputil_nx_flow_format_is_valid(enum nx_flow_format flow_format)
1599 {
1600     return ofputil_nx_flow_format_to_protocol(flow_format) != 0;
1601 }
1602
1603 /* Returns a string version of 'flow_format', which must be a valid NXFF_*
1604  * value. */
1605 const char *
1606 ofputil_nx_flow_format_to_string(enum nx_flow_format flow_format)
1607 {
1608     switch (flow_format) {
1609     case NXFF_OPENFLOW10:
1610         return "openflow10";
1611     case NXFF_NXM:
1612         return "nxm";
1613     default:
1614         NOT_REACHED();
1615     }
1616 }
1617
1618 struct ofpbuf *
1619 ofputil_make_set_packet_in_format(enum nx_packet_in_format packet_in_format)
1620 {
1621     struct nx_set_packet_in_format *spif;
1622     struct ofpbuf *msg;
1623
1624     spif = make_nxmsg(sizeof *spif, NXT_SET_PACKET_IN_FORMAT, &msg);
1625     spif->format = htonl(packet_in_format);
1626
1627     return msg;
1628 }
1629
1630 /* Returns an OpenFlow message that can be used to turn the flow_mod_table_id
1631  * extension on or off (according to 'flow_mod_table_id'). */
1632 struct ofpbuf *
1633 ofputil_make_flow_mod_table_id(bool flow_mod_table_id)
1634 {
1635     struct nx_flow_mod_table_id *nfmti;
1636     struct ofpbuf *msg;
1637
1638     nfmti = make_nxmsg(sizeof *nfmti, NXT_FLOW_MOD_TABLE_ID, &msg);
1639     nfmti->set = flow_mod_table_id;
1640     return msg;
1641 }
1642
1643 /* Converts an OFPT_FLOW_MOD or NXT_FLOW_MOD message 'oh' into an abstract
1644  * flow_mod in 'fm'.  Returns 0 if successful, otherwise an OpenFlow error
1645  * code.
1646  *
1647  * Does not validate the flow_mod actions. */
1648 enum ofperr
1649 ofputil_decode_flow_mod(struct ofputil_flow_mod *fm,
1650                         const struct ofp_header *oh,
1651                         enum ofputil_protocol protocol)
1652 {
1653     const struct ofputil_msg_type *type;
1654     uint16_t command;
1655     struct ofpbuf b;
1656
1657     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1658
1659     ofputil_decode_msg_type(oh, &type);
1660     if (ofputil_msg_type_code(type) == OFPUTIL_OFPT_FLOW_MOD) {
1661         /* Standard OpenFlow flow_mod. */
1662         const struct ofp_flow_mod *ofm;
1663         uint16_t priority;
1664         enum ofperr error;
1665
1666         /* Dissect the message. */
1667         ofm = ofpbuf_pull(&b, sizeof *ofm);
1668         error = ofputil_pull_actions(&b, b.size, &fm->actions, &fm->n_actions);
1669         if (error) {
1670             return error;
1671         }
1672
1673         /* Set priority based on original wildcards.  Normally we'd allow
1674          * ofputil_cls_rule_from_match() to do this for us, but
1675          * ofputil_normalize_rule() can put wildcards where the original flow
1676          * didn't have them. */
1677         priority = ntohs(ofm->priority);
1678         if (!(ofm->match.wildcards & htonl(OFPFW10_ALL))) {
1679             priority = UINT16_MAX;
1680         }
1681
1682         /* Translate the rule. */
1683         ofputil_cls_rule_from_ofp10_match(&ofm->match, priority, &fm->cr);
1684         ofputil_normalize_rule(&fm->cr);
1685
1686         /* Translate the message. */
1687         command = ntohs(ofm->command);
1688         fm->cookie = htonll(0);
1689         fm->cookie_mask = htonll(0);
1690         fm->new_cookie = ofm->cookie;
1691         fm->idle_timeout = ntohs(ofm->idle_timeout);
1692         fm->hard_timeout = ntohs(ofm->hard_timeout);
1693         fm->buffer_id = ntohl(ofm->buffer_id);
1694         fm->out_port = ntohs(ofm->out_port);
1695         fm->flags = ntohs(ofm->flags);
1696     } else if (ofputil_msg_type_code(type) == OFPUTIL_NXT_FLOW_MOD) {
1697         /* Nicira extended flow_mod. */
1698         const struct nx_flow_mod *nfm;
1699         enum ofperr error;
1700
1701         /* Dissect the message. */
1702         nfm = ofpbuf_pull(&b, sizeof *nfm);
1703         error = nx_pull_match(&b, ntohs(nfm->match_len), ntohs(nfm->priority),
1704                               &fm->cr, &fm->cookie, &fm->cookie_mask);
1705         if (error) {
1706             return error;
1707         }
1708         error = ofputil_pull_actions(&b, b.size, &fm->actions, &fm->n_actions);
1709         if (error) {
1710             return error;
1711         }
1712
1713         /* Translate the message. */
1714         command = ntohs(nfm->command);
1715         if ((command & 0xff) == OFPFC_ADD && fm->cookie_mask) {
1716             /* Flow additions may only set a new cookie, not match an
1717              * existing cookie. */
1718             return OFPERR_NXBRC_NXM_INVALID;
1719         }
1720         fm->new_cookie = nfm->cookie;
1721         fm->idle_timeout = ntohs(nfm->idle_timeout);
1722         fm->hard_timeout = ntohs(nfm->hard_timeout);
1723         fm->buffer_id = ntohl(nfm->buffer_id);
1724         fm->out_port = ntohs(nfm->out_port);
1725         fm->flags = ntohs(nfm->flags);
1726     } else {
1727         NOT_REACHED();
1728     }
1729
1730     if (protocol & OFPUTIL_P_TID) {
1731         fm->command = command & 0xff;
1732         fm->table_id = command >> 8;
1733     } else {
1734         fm->command = command;
1735         fm->table_id = 0xff;
1736     }
1737
1738     return 0;
1739 }
1740
1741 /* Converts 'fm' into an OFPT_FLOW_MOD or NXT_FLOW_MOD message according to
1742  * 'protocol' and returns the message. */
1743 struct ofpbuf *
1744 ofputil_encode_flow_mod(const struct ofputil_flow_mod *fm,
1745                         enum ofputil_protocol protocol)
1746 {
1747     size_t actions_len = fm->n_actions * sizeof *fm->actions;
1748     struct ofp_flow_mod *ofm;
1749     struct nx_flow_mod *nfm;
1750     struct ofpbuf *msg;
1751     uint16_t command;
1752     int match_len;
1753
1754     command = (protocol & OFPUTIL_P_TID
1755                ? (fm->command & 0xff) | (fm->table_id << 8)
1756                : fm->command);
1757
1758     switch (protocol) {
1759     case OFPUTIL_P_OF10:
1760     case OFPUTIL_P_OF10_TID:
1761         msg = ofpbuf_new(sizeof *ofm + actions_len);
1762         ofm = put_openflow(sizeof *ofm, OFPT_FLOW_MOD, msg);
1763         ofputil_cls_rule_to_ofp10_match(&fm->cr, &ofm->match);
1764         ofm->cookie = fm->new_cookie;
1765         ofm->command = htons(command);
1766         ofm->idle_timeout = htons(fm->idle_timeout);
1767         ofm->hard_timeout = htons(fm->hard_timeout);
1768         ofm->priority = htons(fm->cr.priority);
1769         ofm->buffer_id = htonl(fm->buffer_id);
1770         ofm->out_port = htons(fm->out_port);
1771         ofm->flags = htons(fm->flags);
1772         break;
1773
1774     case OFPUTIL_P_NXM:
1775     case OFPUTIL_P_NXM_TID:
1776         msg = ofpbuf_new(sizeof *nfm + NXM_TYPICAL_LEN + actions_len);
1777         put_nxmsg(sizeof *nfm, NXT_FLOW_MOD, msg);
1778         nfm = msg->data;
1779         nfm->command = htons(command);
1780         nfm->cookie = fm->new_cookie;
1781         match_len = nx_put_match(msg, false, &fm->cr,
1782                                  fm->cookie, fm->cookie_mask);
1783         nfm = msg->data;
1784         nfm->idle_timeout = htons(fm->idle_timeout);
1785         nfm->hard_timeout = htons(fm->hard_timeout);
1786         nfm->priority = htons(fm->cr.priority);
1787         nfm->buffer_id = htonl(fm->buffer_id);
1788         nfm->out_port = htons(fm->out_port);
1789         nfm->flags = htons(fm->flags);
1790         nfm->match_len = htons(match_len);
1791         break;
1792
1793     default:
1794         NOT_REACHED();
1795     }
1796
1797     ofpbuf_put(msg, fm->actions, actions_len);
1798     update_openflow_length(msg);
1799     return msg;
1800 }
1801
1802 /* Returns a bitmask with a 1-bit for each protocol that could be used to
1803  * send all of the 'n_fm's flow table modification requests in 'fms', and a
1804  * 0-bit for each protocol that is inadequate.
1805  *
1806  * (The return value will have at least one 1-bit.) */
1807 enum ofputil_protocol
1808 ofputil_flow_mod_usable_protocols(const struct ofputil_flow_mod *fms,
1809                                   size_t n_fms)
1810 {
1811     enum ofputil_protocol usable_protocols;
1812     size_t i;
1813
1814     usable_protocols = OFPUTIL_P_ANY;
1815     for (i = 0; i < n_fms; i++) {
1816         const struct ofputil_flow_mod *fm = &fms[i];
1817
1818         usable_protocols &= ofputil_usable_protocols(&fm->cr);
1819         if (fm->table_id != 0xff) {
1820             usable_protocols &= OFPUTIL_P_TID;
1821         }
1822
1823         /* Matching of the cookie is only supported through NXM. */
1824         if (fm->cookie_mask != htonll(0)) {
1825             usable_protocols &= OFPUTIL_P_NXM_ANY;
1826         }
1827     }
1828     assert(usable_protocols);
1829
1830     return usable_protocols;
1831 }
1832
1833 static enum ofperr
1834 ofputil_decode_ofpst_flow_request(struct ofputil_flow_stats_request *fsr,
1835                                   const struct ofp_header *oh,
1836                                   bool aggregate)
1837 {
1838     const struct ofp_flow_stats_request *ofsr =
1839         (const struct ofp_flow_stats_request *) oh;
1840
1841     fsr->aggregate = aggregate;
1842     ofputil_cls_rule_from_ofp10_match(&ofsr->match, 0, &fsr->match);
1843     fsr->out_port = ntohs(ofsr->out_port);
1844     fsr->table_id = ofsr->table_id;
1845     fsr->cookie = fsr->cookie_mask = htonll(0);
1846
1847     return 0;
1848 }
1849
1850 static enum ofperr
1851 ofputil_decode_nxst_flow_request(struct ofputil_flow_stats_request *fsr,
1852                                  const struct ofp_header *oh,
1853                                  bool aggregate)
1854 {
1855     const struct nx_flow_stats_request *nfsr;
1856     struct ofpbuf b;
1857     enum ofperr error;
1858
1859     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1860
1861     nfsr = ofpbuf_pull(&b, sizeof *nfsr);
1862     error = nx_pull_match(&b, ntohs(nfsr->match_len), 0, &fsr->match,
1863                           &fsr->cookie, &fsr->cookie_mask);
1864     if (error) {
1865         return error;
1866     }
1867     if (b.size) {
1868         return OFPERR_OFPBRC_BAD_LEN;
1869     }
1870
1871     fsr->aggregate = aggregate;
1872     fsr->out_port = ntohs(nfsr->out_port);
1873     fsr->table_id = nfsr->table_id;
1874
1875     return 0;
1876 }
1877
1878 /* Converts an OFPST_FLOW, OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE
1879  * request 'oh', into an abstract flow_stats_request in 'fsr'.  Returns 0 if
1880  * successful, otherwise an OpenFlow error code. */
1881 enum ofperr
1882 ofputil_decode_flow_stats_request(struct ofputil_flow_stats_request *fsr,
1883                                   const struct ofp_header *oh)
1884 {
1885     const struct ofputil_msg_type *type;
1886     struct ofpbuf b;
1887     int code;
1888
1889     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1890
1891     ofputil_decode_msg_type(oh, &type);
1892     code = ofputil_msg_type_code(type);
1893     switch (code) {
1894     case OFPUTIL_OFPST_FLOW_REQUEST:
1895         return ofputil_decode_ofpst_flow_request(fsr, oh, false);
1896
1897     case OFPUTIL_OFPST_AGGREGATE_REQUEST:
1898         return ofputil_decode_ofpst_flow_request(fsr, oh, true);
1899
1900     case OFPUTIL_NXST_FLOW_REQUEST:
1901         return ofputil_decode_nxst_flow_request(fsr, oh, false);
1902
1903     case OFPUTIL_NXST_AGGREGATE_REQUEST:
1904         return ofputil_decode_nxst_flow_request(fsr, oh, true);
1905
1906     default:
1907         /* Hey, the caller lied. */
1908         NOT_REACHED();
1909     }
1910 }
1911
1912 /* Converts abstract flow_stats_request 'fsr' into an OFPST_FLOW,
1913  * OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE request 'oh' according to
1914  * 'protocol', and returns the message. */
1915 struct ofpbuf *
1916 ofputil_encode_flow_stats_request(const struct ofputil_flow_stats_request *fsr,
1917                                   enum ofputil_protocol protocol)
1918 {
1919     struct ofpbuf *msg;
1920
1921     switch (protocol) {
1922     case OFPUTIL_P_OF10:
1923     case OFPUTIL_P_OF10_TID: {
1924         struct ofp_flow_stats_request *ofsr;
1925         int type;
1926
1927         type = fsr->aggregate ? OFPST_AGGREGATE : OFPST_FLOW;
1928         ofsr = ofputil_make_stats_request(sizeof *ofsr, type, 0, &msg);
1929         ofputil_cls_rule_to_ofp10_match(&fsr->match, &ofsr->match);
1930         ofsr->table_id = fsr->table_id;
1931         ofsr->out_port = htons(fsr->out_port);
1932         break;
1933     }
1934
1935     case OFPUTIL_P_NXM:
1936     case OFPUTIL_P_NXM_TID: {
1937         struct nx_flow_stats_request *nfsr;
1938         int match_len;
1939         int subtype;
1940
1941         subtype = fsr->aggregate ? NXST_AGGREGATE : NXST_FLOW;
1942         ofputil_make_stats_request(sizeof *nfsr, OFPST_VENDOR, subtype, &msg);
1943         match_len = nx_put_match(msg, false, &fsr->match,
1944                                  fsr->cookie, fsr->cookie_mask);
1945
1946         nfsr = msg->data;
1947         nfsr->out_port = htons(fsr->out_port);
1948         nfsr->match_len = htons(match_len);
1949         nfsr->table_id = fsr->table_id;
1950         break;
1951     }
1952
1953     default:
1954         NOT_REACHED();
1955     }
1956
1957     return msg;
1958 }
1959
1960 /* Returns a bitmask with a 1-bit for each protocol that could be used to
1961  * accurately encode 'fsr', and a 0-bit for each protocol that is inadequate.
1962  *
1963  * (The return value will have at least one 1-bit.) */
1964 enum ofputil_protocol
1965 ofputil_flow_stats_request_usable_protocols(
1966     const struct ofputil_flow_stats_request *fsr)
1967 {
1968     enum ofputil_protocol usable_protocols;
1969
1970     usable_protocols = ofputil_usable_protocols(&fsr->match);
1971     if (fsr->cookie_mask != htonll(0)) {
1972         usable_protocols &= OFPUTIL_P_NXM_ANY;
1973     }
1974     return usable_protocols;
1975 }
1976
1977 /* Converts an OFPST_FLOW or NXST_FLOW reply in 'msg' into an abstract
1978  * ofputil_flow_stats in 'fs'.
1979  *
1980  * Multiple OFPST_FLOW or NXST_FLOW replies can be packed into a single
1981  * OpenFlow message.  Calling this function multiple times for a single 'msg'
1982  * iterates through the replies.  The caller must initially leave 'msg''s layer
1983  * pointers null and not modify them between calls.
1984  *
1985  * Most switches don't send the values needed to populate fs->idle_age and
1986  * fs->hard_age, so those members will usually be set to 0.  If the switch from
1987  * which 'msg' originated is known to implement NXT_FLOW_AGE, then pass
1988  * 'flow_age_extension' as true so that the contents of 'msg' determine the
1989  * 'idle_age' and 'hard_age' members in 'fs'.
1990  *
1991  * Returns 0 if successful, EOF if no replies were left in this 'msg',
1992  * otherwise a positive errno value. */
1993 int
1994 ofputil_decode_flow_stats_reply(struct ofputil_flow_stats *fs,
1995                                 struct ofpbuf *msg,
1996                                 bool flow_age_extension)
1997 {
1998     const struct ofputil_msg_type *type;
1999     int code;
2000
2001     ofputil_decode_msg_type(msg->l2 ? msg->l2 : msg->data, &type);
2002     code = ofputil_msg_type_code(type);
2003     if (!msg->l2) {
2004         msg->l2 = msg->data;
2005         if (code == OFPUTIL_OFPST_FLOW_REPLY) {
2006             ofpbuf_pull(msg, sizeof(struct ofp_stats_msg));
2007         } else if (code == OFPUTIL_NXST_FLOW_REPLY) {
2008             ofpbuf_pull(msg, sizeof(struct nicira_stats_msg));
2009         } else {
2010             NOT_REACHED();
2011         }
2012     }
2013
2014     if (!msg->size) {
2015         return EOF;
2016     } else if (code == OFPUTIL_OFPST_FLOW_REPLY) {
2017         const struct ofp_flow_stats *ofs;
2018         size_t length;
2019
2020         ofs = ofpbuf_try_pull(msg, sizeof *ofs);
2021         if (!ofs) {
2022             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply has %zu leftover "
2023                          "bytes at end", msg->size);
2024             return EINVAL;
2025         }
2026
2027         length = ntohs(ofs->length);
2028         if (length < sizeof *ofs) {
2029             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply claims invalid "
2030                          "length %zu", length);
2031             return EINVAL;
2032         }
2033
2034         if (ofputil_pull_actions(msg, length - sizeof *ofs,
2035                                  &fs->actions, &fs->n_actions)) {
2036             return EINVAL;
2037         }
2038
2039         fs->cookie = get_32aligned_be64(&ofs->cookie);
2040         ofputil_cls_rule_from_ofp10_match(&ofs->match, ntohs(ofs->priority),
2041                                           &fs->rule);
2042         fs->table_id = ofs->table_id;
2043         fs->duration_sec = ntohl(ofs->duration_sec);
2044         fs->duration_nsec = ntohl(ofs->duration_nsec);
2045         fs->idle_timeout = ntohs(ofs->idle_timeout);
2046         fs->hard_timeout = ntohs(ofs->hard_timeout);
2047         fs->idle_age = -1;
2048         fs->hard_age = -1;
2049         fs->packet_count = ntohll(get_32aligned_be64(&ofs->packet_count));
2050         fs->byte_count = ntohll(get_32aligned_be64(&ofs->byte_count));
2051     } else if (code == OFPUTIL_NXST_FLOW_REPLY) {
2052         const struct nx_flow_stats *nfs;
2053         size_t match_len, length;
2054
2055         nfs = ofpbuf_try_pull(msg, sizeof *nfs);
2056         if (!nfs) {
2057             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply has %zu leftover "
2058                          "bytes at end", msg->size);
2059             return EINVAL;
2060         }
2061
2062         length = ntohs(nfs->length);
2063         match_len = ntohs(nfs->match_len);
2064         if (length < sizeof *nfs + ROUND_UP(match_len, 8)) {
2065             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply with match_len=%zu "
2066                          "claims invalid length %zu", match_len, length);
2067             return EINVAL;
2068         }
2069         if (nx_pull_match(msg, match_len, ntohs(nfs->priority), &fs->rule,
2070                           NULL, NULL)) {
2071             return EINVAL;
2072         }
2073
2074         if (ofputil_pull_actions(msg,
2075                                  length - sizeof *nfs - ROUND_UP(match_len, 8),
2076                                  &fs->actions, &fs->n_actions)) {
2077             return EINVAL;
2078         }
2079
2080         fs->cookie = nfs->cookie;
2081         fs->table_id = nfs->table_id;
2082         fs->duration_sec = ntohl(nfs->duration_sec);
2083         fs->duration_nsec = ntohl(nfs->duration_nsec);
2084         fs->idle_timeout = ntohs(nfs->idle_timeout);
2085         fs->hard_timeout = ntohs(nfs->hard_timeout);
2086         fs->idle_age = -1;
2087         fs->hard_age = -1;
2088         if (flow_age_extension) {
2089             if (nfs->idle_age) {
2090                 fs->idle_age = ntohs(nfs->idle_age) - 1;
2091             }
2092             if (nfs->hard_age) {
2093                 fs->hard_age = ntohs(nfs->hard_age) - 1;
2094             }
2095         }
2096         fs->packet_count = ntohll(nfs->packet_count);
2097         fs->byte_count = ntohll(nfs->byte_count);
2098     } else {
2099         NOT_REACHED();
2100     }
2101
2102     return 0;
2103 }
2104
2105 /* Returns 'count' unchanged except that UINT64_MAX becomes 0.
2106  *
2107  * We use this in situations where OVS internally uses UINT64_MAX to mean
2108  * "value unknown" but OpenFlow 1.0 does not define any unknown value. */
2109 static uint64_t
2110 unknown_to_zero(uint64_t count)
2111 {
2112     return count != UINT64_MAX ? count : 0;
2113 }
2114
2115 /* Appends an OFPST_FLOW or NXST_FLOW reply that contains the data in 'fs' to
2116  * those already present in the list of ofpbufs in 'replies'.  'replies' should
2117  * have been initialized with ofputil_start_stats_reply(). */
2118 void
2119 ofputil_append_flow_stats_reply(const struct ofputil_flow_stats *fs,
2120                                 struct list *replies)
2121 {
2122     size_t act_len = fs->n_actions * sizeof *fs->actions;
2123     const struct ofp_stats_msg *osm;
2124
2125     osm = ofpbuf_from_list(list_back(replies))->data;
2126     if (osm->type == htons(OFPST_FLOW)) {
2127         size_t len = offsetof(struct ofp_flow_stats, actions) + act_len;
2128         struct ofp_flow_stats *ofs;
2129
2130         ofs = ofputil_append_stats_reply(len, replies);
2131         ofs->length = htons(len);
2132         ofs->table_id = fs->table_id;
2133         ofs->pad = 0;
2134         ofputil_cls_rule_to_ofp10_match(&fs->rule, &ofs->match);
2135         ofs->duration_sec = htonl(fs->duration_sec);
2136         ofs->duration_nsec = htonl(fs->duration_nsec);
2137         ofs->priority = htons(fs->rule.priority);
2138         ofs->idle_timeout = htons(fs->idle_timeout);
2139         ofs->hard_timeout = htons(fs->hard_timeout);
2140         memset(ofs->pad2, 0, sizeof ofs->pad2);
2141         put_32aligned_be64(&ofs->cookie, fs->cookie);
2142         put_32aligned_be64(&ofs->packet_count,
2143                            htonll(unknown_to_zero(fs->packet_count)));
2144         put_32aligned_be64(&ofs->byte_count,
2145                            htonll(unknown_to_zero(fs->byte_count)));
2146         memcpy(ofs->actions, fs->actions, act_len);
2147     } else if (osm->type == htons(OFPST_VENDOR)) {
2148         struct nx_flow_stats *nfs;
2149         struct ofpbuf *msg;
2150         size_t start_len;
2151
2152         msg = ofputil_reserve_stats_reply(
2153             sizeof *nfs + NXM_MAX_LEN + act_len, replies);
2154         start_len = msg->size;
2155
2156         nfs = ofpbuf_put_uninit(msg, sizeof *nfs);
2157         nfs->table_id = fs->table_id;
2158         nfs->pad = 0;
2159         nfs->duration_sec = htonl(fs->duration_sec);
2160         nfs->duration_nsec = htonl(fs->duration_nsec);
2161         nfs->priority = htons(fs->rule.priority);
2162         nfs->idle_timeout = htons(fs->idle_timeout);
2163         nfs->hard_timeout = htons(fs->hard_timeout);
2164         nfs->idle_age = htons(fs->idle_age < 0 ? 0
2165                               : fs->idle_age < UINT16_MAX ? fs->idle_age + 1
2166                               : UINT16_MAX);
2167         nfs->hard_age = htons(fs->hard_age < 0 ? 0
2168                               : fs->hard_age < UINT16_MAX ? fs->hard_age + 1
2169                               : UINT16_MAX);
2170         nfs->match_len = htons(nx_put_match(msg, false, &fs->rule, 0, 0));
2171         nfs->cookie = fs->cookie;
2172         nfs->packet_count = htonll(fs->packet_count);
2173         nfs->byte_count = htonll(fs->byte_count);
2174         ofpbuf_put(msg, fs->actions, act_len);
2175         nfs->length = htons(msg->size - start_len);
2176     } else {
2177         NOT_REACHED();
2178     }
2179 }
2180
2181 /* Converts abstract ofputil_aggregate_stats 'stats' into an OFPST_AGGREGATE or
2182  * NXST_AGGREGATE reply according to 'protocol', and returns the message. */
2183 struct ofpbuf *
2184 ofputil_encode_aggregate_stats_reply(
2185     const struct ofputil_aggregate_stats *stats,
2186     const struct ofp_stats_msg *request)
2187 {
2188     struct ofpbuf *msg;
2189
2190     if (request->type == htons(OFPST_AGGREGATE)) {
2191         struct ofp_aggregate_stats_reply *asr;
2192
2193         asr = ofputil_make_stats_reply(sizeof *asr, request, &msg);
2194         put_32aligned_be64(&asr->packet_count,
2195                            htonll(unknown_to_zero(stats->packet_count)));
2196         put_32aligned_be64(&asr->byte_count,
2197                            htonll(unknown_to_zero(stats->byte_count)));
2198         asr->flow_count = htonl(stats->flow_count);
2199     } else if (request->type == htons(OFPST_VENDOR)) {
2200         struct nx_aggregate_stats_reply *nasr;
2201
2202         nasr = ofputil_make_stats_reply(sizeof *nasr, request, &msg);
2203         assert(nasr->nsm.subtype == htonl(NXST_AGGREGATE));
2204         nasr->packet_count = htonll(stats->packet_count);
2205         nasr->byte_count = htonll(stats->byte_count);
2206         nasr->flow_count = htonl(stats->flow_count);
2207     } else {
2208         NOT_REACHED();
2209     }
2210
2211     return msg;
2212 }
2213
2214 /* Converts an OFPT_FLOW_REMOVED or NXT_FLOW_REMOVED message 'oh' into an
2215  * abstract ofputil_flow_removed in 'fr'.  Returns 0 if successful, otherwise
2216  * an OpenFlow error code. */
2217 enum ofperr
2218 ofputil_decode_flow_removed(struct ofputil_flow_removed *fr,
2219                             const struct ofp_header *oh)
2220 {
2221     const struct ofputil_msg_type *type;
2222     enum ofputil_msg_code code;
2223
2224     ofputil_decode_msg_type(oh, &type);
2225     code = ofputil_msg_type_code(type);
2226     if (code == OFPUTIL_OFPT_FLOW_REMOVED) {
2227         const struct ofp_flow_removed *ofr;
2228
2229         ofr = (const struct ofp_flow_removed *) oh;
2230         ofputil_cls_rule_from_ofp10_match(&ofr->match, ntohs(ofr->priority),
2231                                           &fr->rule);
2232         fr->cookie = ofr->cookie;
2233         fr->reason = ofr->reason;
2234         fr->duration_sec = ntohl(ofr->duration_sec);
2235         fr->duration_nsec = ntohl(ofr->duration_nsec);
2236         fr->idle_timeout = ntohs(ofr->idle_timeout);
2237         fr->packet_count = ntohll(ofr->packet_count);
2238         fr->byte_count = ntohll(ofr->byte_count);
2239     } else if (code == OFPUTIL_NXT_FLOW_REMOVED) {
2240         struct nx_flow_removed *nfr;
2241         struct ofpbuf b;
2242         int error;
2243
2244         ofpbuf_use_const(&b, oh, ntohs(oh->length));
2245
2246         nfr = ofpbuf_pull(&b, sizeof *nfr);
2247         error = nx_pull_match(&b, ntohs(nfr->match_len), ntohs(nfr->priority),
2248                               &fr->rule, NULL, NULL);
2249         if (error) {
2250             return error;
2251         }
2252         if (b.size) {
2253             return OFPERR_OFPBRC_BAD_LEN;
2254         }
2255
2256         fr->cookie = nfr->cookie;
2257         fr->reason = nfr->reason;
2258         fr->duration_sec = ntohl(nfr->duration_sec);
2259         fr->duration_nsec = ntohl(nfr->duration_nsec);
2260         fr->idle_timeout = ntohs(nfr->idle_timeout);
2261         fr->packet_count = ntohll(nfr->packet_count);
2262         fr->byte_count = ntohll(nfr->byte_count);
2263     } else {
2264         NOT_REACHED();
2265     }
2266
2267     return 0;
2268 }
2269
2270 /* Converts abstract ofputil_flow_removed 'fr' into an OFPT_FLOW_REMOVED or
2271  * NXT_FLOW_REMOVED message 'oh' according to 'protocol', and returns the
2272  * message. */
2273 struct ofpbuf *
2274 ofputil_encode_flow_removed(const struct ofputil_flow_removed *fr,
2275                             enum ofputil_protocol protocol)
2276 {
2277     struct ofpbuf *msg;
2278
2279     switch (protocol) {
2280     case OFPUTIL_P_OF10:
2281     case OFPUTIL_P_OF10_TID: {
2282         struct ofp_flow_removed *ofr;
2283
2284         ofr = make_openflow_xid(sizeof *ofr, OFPT_FLOW_REMOVED, htonl(0),
2285                                 &msg);
2286         ofputil_cls_rule_to_ofp10_match(&fr->rule, &ofr->match);
2287         ofr->cookie = fr->cookie;
2288         ofr->priority = htons(fr->rule.priority);
2289         ofr->reason = fr->reason;
2290         ofr->duration_sec = htonl(fr->duration_sec);
2291         ofr->duration_nsec = htonl(fr->duration_nsec);
2292         ofr->idle_timeout = htons(fr->idle_timeout);
2293         ofr->packet_count = htonll(unknown_to_zero(fr->packet_count));
2294         ofr->byte_count = htonll(unknown_to_zero(fr->byte_count));
2295         break;
2296     }
2297
2298     case OFPUTIL_P_NXM:
2299     case OFPUTIL_P_NXM_TID: {
2300         struct nx_flow_removed *nfr;
2301         int match_len;
2302
2303         make_nxmsg_xid(sizeof *nfr, NXT_FLOW_REMOVED, htonl(0), &msg);
2304         match_len = nx_put_match(msg, false, &fr->rule, 0, 0);
2305
2306         nfr = msg->data;
2307         nfr->cookie = fr->cookie;
2308         nfr->priority = htons(fr->rule.priority);
2309         nfr->reason = fr->reason;
2310         nfr->duration_sec = htonl(fr->duration_sec);
2311         nfr->duration_nsec = htonl(fr->duration_nsec);
2312         nfr->idle_timeout = htons(fr->idle_timeout);
2313         nfr->match_len = htons(match_len);
2314         nfr->packet_count = htonll(fr->packet_count);
2315         nfr->byte_count = htonll(fr->byte_count);
2316         break;
2317     }
2318
2319     default:
2320         NOT_REACHED();
2321     }
2322
2323     return msg;
2324 }
2325
2326 enum ofperr
2327 ofputil_decode_packet_in(struct ofputil_packet_in *pin,
2328                          const struct ofp_header *oh)
2329 {
2330     const struct ofputil_msg_type *type;
2331     enum ofputil_msg_code code;
2332
2333     ofputil_decode_msg_type(oh, &type);
2334     code = ofputil_msg_type_code(type);
2335     memset(pin, 0, sizeof *pin);
2336
2337     if (code == OFPUTIL_OFPT_PACKET_IN) {
2338         const struct ofp_packet_in *opi = (const struct ofp_packet_in *) oh;
2339
2340         pin->packet = opi->data;
2341         pin->packet_len = ntohs(opi->header.length)
2342             - offsetof(struct ofp_packet_in, data);
2343
2344         pin->fmd.in_port = ntohs(opi->in_port);
2345         pin->reason = opi->reason;
2346         pin->buffer_id = ntohl(opi->buffer_id);
2347         pin->total_len = ntohs(opi->total_len);
2348     } else if (code == OFPUTIL_NXT_PACKET_IN) {
2349         const struct nx_packet_in *npi;
2350         struct cls_rule rule;
2351         struct ofpbuf b;
2352         int error;
2353
2354         ofpbuf_use_const(&b, oh, ntohs(oh->length));
2355
2356         npi = ofpbuf_pull(&b, sizeof *npi);
2357         error = nx_pull_match_loose(&b, ntohs(npi->match_len), 0, &rule, NULL,
2358                                     NULL);
2359         if (error) {
2360             return error;
2361         }
2362
2363         if (!ofpbuf_try_pull(&b, 2)) {
2364             return OFPERR_OFPBRC_BAD_LEN;
2365         }
2366
2367         pin->packet = b.data;
2368         pin->packet_len = b.size;
2369         pin->reason = npi->reason;
2370         pin->table_id = npi->table_id;
2371         pin->cookie = npi->cookie;
2372
2373         pin->fmd.in_port = rule.flow.in_port;
2374
2375         pin->fmd.tun_id = rule.flow.tun_id;
2376         pin->fmd.tun_id_mask = rule.wc.tun_id_mask;
2377
2378         pin->fmd.metadata = rule.flow.metadata;
2379         pin->fmd.metadata_mask = rule.wc.metadata_mask;
2380
2381         memcpy(pin->fmd.regs, rule.flow.regs, sizeof pin->fmd.regs);
2382         memcpy(pin->fmd.reg_masks, rule.wc.reg_masks,
2383                sizeof pin->fmd.reg_masks);
2384
2385         pin->buffer_id = ntohl(npi->buffer_id);
2386         pin->total_len = ntohs(npi->total_len);
2387     } else {
2388         NOT_REACHED();
2389     }
2390
2391     return 0;
2392 }
2393
2394 /* Converts abstract ofputil_packet_in 'pin' into a PACKET_IN message
2395  * in the format specified by 'packet_in_format'.  */
2396 struct ofpbuf *
2397 ofputil_encode_packet_in(const struct ofputil_packet_in *pin,
2398                          enum nx_packet_in_format packet_in_format)
2399 {
2400     size_t send_len = MIN(pin->send_len, pin->packet_len);
2401     struct ofpbuf *packet;
2402
2403     /* Add OFPT_PACKET_IN. */
2404     if (packet_in_format == NXPIF_OPENFLOW10) {
2405         size_t header_len = offsetof(struct ofp_packet_in, data);
2406         struct ofp_packet_in *opi;
2407
2408         packet = ofpbuf_new(send_len + header_len);
2409         opi = ofpbuf_put_zeros(packet, header_len);
2410         opi->header.version = OFP10_VERSION;
2411         opi->header.type = OFPT_PACKET_IN;
2412         opi->total_len = htons(pin->total_len);
2413         opi->in_port = htons(pin->fmd.in_port);
2414         opi->reason = pin->reason;
2415         opi->buffer_id = htonl(pin->buffer_id);
2416
2417         ofpbuf_put(packet, pin->packet, send_len);
2418     } else if (packet_in_format == NXPIF_NXM) {
2419         struct nx_packet_in *npi;
2420         struct cls_rule rule;
2421         size_t match_len;
2422         size_t i;
2423
2424         /* Estimate of required PACKET_IN length includes the NPI header, space
2425          * for the match (2 times sizeof the metadata seems like enough), 2
2426          * bytes for padding, and the packet length. */
2427         packet = ofpbuf_new(sizeof *npi + sizeof(struct flow_metadata) * 2
2428                             + 2 + send_len);
2429
2430         cls_rule_init_catchall(&rule, 0);
2431         cls_rule_set_tun_id_masked(&rule, pin->fmd.tun_id,
2432                                    pin->fmd.tun_id_mask);
2433         cls_rule_set_metadata_masked(&rule, pin->fmd.metadata,
2434                                    pin->fmd.metadata_mask);
2435
2436
2437         for (i = 0; i < FLOW_N_REGS; i++) {
2438             cls_rule_set_reg_masked(&rule, i, pin->fmd.regs[i],
2439                                     pin->fmd.reg_masks[i]);
2440         }
2441
2442         cls_rule_set_in_port(&rule, pin->fmd.in_port);
2443
2444         ofpbuf_put_zeros(packet, sizeof *npi);
2445         match_len = nx_put_match(packet, false, &rule, 0, 0);
2446         ofpbuf_put_zeros(packet, 2);
2447         ofpbuf_put(packet, pin->packet, send_len);
2448
2449         npi = packet->data;
2450         npi->nxh.header.version = OFP10_VERSION;
2451         npi->nxh.header.type = OFPT_VENDOR;
2452         npi->nxh.vendor = htonl(NX_VENDOR_ID);
2453         npi->nxh.subtype = htonl(NXT_PACKET_IN);
2454
2455         npi->buffer_id = htonl(pin->buffer_id);
2456         npi->total_len = htons(pin->total_len);
2457         npi->reason = pin->reason;
2458         npi->table_id = pin->table_id;
2459         npi->cookie = pin->cookie;
2460         npi->match_len = htons(match_len);
2461     } else {
2462         NOT_REACHED();
2463     }
2464     update_openflow_length(packet);
2465
2466     return packet;
2467 }
2468
2469 const char *
2470 ofputil_packet_in_reason_to_string(enum ofp_packet_in_reason reason)
2471 {
2472     static char s[INT_STRLEN(int) + 1];
2473
2474     switch (reason) {
2475     case OFPR_NO_MATCH:
2476         return "no_match";
2477     case OFPR_ACTION:
2478         return "action";
2479     case OFPR_INVALID_TTL:
2480         return "invalid_ttl";
2481
2482     case OFPR_N_REASONS:
2483     default:
2484         sprintf(s, "%d", (int) reason);
2485         return s;
2486     }
2487 }
2488
2489 bool
2490 ofputil_packet_in_reason_from_string(const char *s,
2491                                      enum ofp_packet_in_reason *reason)
2492 {
2493     int i;
2494
2495     for (i = 0; i < OFPR_N_REASONS; i++) {
2496         if (!strcasecmp(s, ofputil_packet_in_reason_to_string(i))) {
2497             *reason = i;
2498             return true;
2499         }
2500     }
2501     return false;
2502 }
2503
2504 enum ofperr
2505 ofputil_decode_packet_out(struct ofputil_packet_out *po,
2506                           const struct ofp_packet_out *opo)
2507 {
2508     enum ofperr error;
2509     struct ofpbuf b;
2510
2511     po->buffer_id = ntohl(opo->buffer_id);
2512     po->in_port = ntohs(opo->in_port);
2513     if (po->in_port >= OFPP_MAX && po->in_port != OFPP_LOCAL
2514         && po->in_port != OFPP_NONE && po->in_port != OFPP_CONTROLLER) {
2515         VLOG_WARN_RL(&bad_ofmsg_rl, "packet-out has bad input port %#"PRIx16,
2516                      po->in_port);
2517         return OFPERR_NXBRC_BAD_IN_PORT;
2518     }
2519
2520     ofpbuf_use_const(&b, opo, ntohs(opo->header.length));
2521     ofpbuf_pull(&b, sizeof *opo);
2522
2523     error = ofputil_pull_actions(&b, ntohs(opo->actions_len),
2524                                  &po->actions, &po->n_actions);
2525     if (error) {
2526         return error;
2527     }
2528
2529     if (po->buffer_id == UINT32_MAX) {
2530         po->packet = b.data;
2531         po->packet_len = b.size;
2532     } else {
2533         po->packet = NULL;
2534         po->packet_len = 0;
2535     }
2536
2537     return 0;
2538 }
2539 \f
2540 /* ofputil_phy_port */
2541
2542 /* NETDEV_F_* to and from OFPPF_* and OFPPF10_*. */
2543 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_HD    == OFPPF_10MB_HD);  /* bit 0 */
2544 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_FD    == OFPPF_10MB_FD);  /* bit 1 */
2545 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_HD   == OFPPF_100MB_HD); /* bit 2 */
2546 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_FD   == OFPPF_100MB_FD); /* bit 3 */
2547 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_HD     == OFPPF_1GB_HD);   /* bit 4 */
2548 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_FD     == OFPPF_1GB_FD);   /* bit 5 */
2549 BUILD_ASSERT_DECL((int) NETDEV_F_10GB_FD    == OFPPF_10GB_FD);  /* bit 6 */
2550
2551 /* NETDEV_F_ bits 11...15 are OFPPF10_ bits 7...11: */
2552 BUILD_ASSERT_DECL((int) NETDEV_F_COPPER == (OFPPF10_COPPER << 4));
2553 BUILD_ASSERT_DECL((int) NETDEV_F_FIBER == (OFPPF10_FIBER << 4));
2554 BUILD_ASSERT_DECL((int) NETDEV_F_AUTONEG == (OFPPF10_AUTONEG << 4));
2555 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE == (OFPPF10_PAUSE << 4));
2556 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE_ASYM == (OFPPF10_PAUSE_ASYM << 4));
2557
2558 static enum netdev_features
2559 netdev_port_features_from_ofp10(ovs_be32 ofp10_)
2560 {
2561     uint32_t ofp10 = ntohl(ofp10_);
2562     return (ofp10 & 0x7f) | ((ofp10 & 0xf80) << 4);
2563 }
2564
2565 static ovs_be32
2566 netdev_port_features_to_ofp10(enum netdev_features features)
2567 {
2568     return htonl((features & 0x7f) | ((features & 0xf800) >> 4));
2569 }
2570
2571 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_HD    == OFPPF_10MB_HD);     /* bit 0 */
2572 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_FD    == OFPPF_10MB_FD);     /* bit 1 */
2573 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_HD   == OFPPF_100MB_HD);    /* bit 2 */
2574 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_FD   == OFPPF_100MB_FD);    /* bit 3 */
2575 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_HD     == OFPPF_1GB_HD);      /* bit 4 */
2576 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_FD     == OFPPF_1GB_FD);      /* bit 5 */
2577 BUILD_ASSERT_DECL((int) NETDEV_F_10GB_FD    == OFPPF_10GB_FD);     /* bit 6 */
2578 BUILD_ASSERT_DECL((int) NETDEV_F_40GB_FD    == OFPPF11_40GB_FD);   /* bit 7 */
2579 BUILD_ASSERT_DECL((int) NETDEV_F_100GB_FD   == OFPPF11_100GB_FD);  /* bit 8 */
2580 BUILD_ASSERT_DECL((int) NETDEV_F_1TB_FD     == OFPPF11_1TB_FD);    /* bit 9 */
2581 BUILD_ASSERT_DECL((int) NETDEV_F_OTHER      == OFPPF11_OTHER);     /* bit 10 */
2582 BUILD_ASSERT_DECL((int) NETDEV_F_COPPER     == OFPPF11_COPPER);    /* bit 11 */
2583 BUILD_ASSERT_DECL((int) NETDEV_F_FIBER      == OFPPF11_FIBER);     /* bit 12 */
2584 BUILD_ASSERT_DECL((int) NETDEV_F_AUTONEG    == OFPPF11_AUTONEG);   /* bit 13 */
2585 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE      == OFPPF11_PAUSE);     /* bit 14 */
2586 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE_ASYM == OFPPF11_PAUSE_ASYM);/* bit 15 */
2587
2588 static enum netdev_features
2589 netdev_port_features_from_ofp11(ovs_be32 ofp11)
2590 {
2591     return ntohl(ofp11) & 0xffff;
2592 }
2593
2594 static ovs_be32
2595 netdev_port_features_to_ofp11(enum netdev_features features)
2596 {
2597     return htonl(features & 0xffff);
2598 }
2599
2600 static enum ofperr
2601 ofputil_decode_ofp10_phy_port(struct ofputil_phy_port *pp,
2602                               const struct ofp10_phy_port *opp)
2603 {
2604     memset(pp, 0, sizeof *pp);
2605
2606     pp->port_no = ntohs(opp->port_no);
2607     memcpy(pp->hw_addr, opp->hw_addr, OFP_ETH_ALEN);
2608     ovs_strlcpy(pp->name, opp->name, OFP_MAX_PORT_NAME_LEN);
2609
2610     pp->config = ntohl(opp->config) & OFPPC10_ALL;
2611     pp->state = ntohl(opp->state) & OFPPS10_ALL;
2612
2613     pp->curr = netdev_port_features_from_ofp10(opp->curr);
2614     pp->advertised = netdev_port_features_from_ofp10(opp->advertised);
2615     pp->supported = netdev_port_features_from_ofp10(opp->supported);
2616     pp->peer = netdev_port_features_from_ofp10(opp->peer);
2617
2618     pp->curr_speed = netdev_features_to_bps(pp->curr) / 1000;
2619     pp->max_speed = netdev_features_to_bps(pp->supported) / 1000;
2620
2621     return 0;
2622 }
2623
2624 static enum ofperr
2625 ofputil_decode_ofp11_port(struct ofputil_phy_port *pp,
2626                           const struct ofp11_port *op)
2627 {
2628     enum ofperr error;
2629
2630     memset(pp, 0, sizeof *pp);
2631
2632     error = ofputil_port_from_ofp11(op->port_no, &pp->port_no);
2633     if (error) {
2634         return error;
2635     }
2636     memcpy(pp->hw_addr, op->hw_addr, OFP_ETH_ALEN);
2637     ovs_strlcpy(pp->name, op->name, OFP_MAX_PORT_NAME_LEN);
2638
2639     pp->config = ntohl(op->config) & OFPPC11_ALL;
2640     pp->state = ntohl(op->state) & OFPPC11_ALL;
2641
2642     pp->curr = netdev_port_features_from_ofp11(op->curr);
2643     pp->advertised = netdev_port_features_from_ofp11(op->advertised);
2644     pp->supported = netdev_port_features_from_ofp11(op->supported);
2645     pp->peer = netdev_port_features_from_ofp11(op->peer);
2646
2647     pp->curr_speed = ntohl(op->curr_speed);
2648     pp->max_speed = ntohl(op->max_speed);
2649
2650     return 0;
2651 }
2652
2653 static size_t
2654 ofputil_get_phy_port_size(uint8_t ofp_version)
2655 {
2656     return ofp_version == OFP10_VERSION ? sizeof(struct ofp10_phy_port)
2657                                         : sizeof(struct ofp11_port);
2658 }
2659
2660 static void
2661 ofputil_encode_ofp10_phy_port(const struct ofputil_phy_port *pp,
2662                               struct ofp10_phy_port *opp)
2663 {
2664     memset(opp, 0, sizeof *opp);
2665
2666     opp->port_no = htons(pp->port_no);
2667     memcpy(opp->hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2668     ovs_strlcpy(opp->name, pp->name, OFP_MAX_PORT_NAME_LEN);
2669
2670     opp->config = htonl(pp->config & OFPPC10_ALL);
2671     opp->state = htonl(pp->state & OFPPS10_ALL);
2672
2673     opp->curr = netdev_port_features_to_ofp10(pp->curr);
2674     opp->advertised = netdev_port_features_to_ofp10(pp->advertised);
2675     opp->supported = netdev_port_features_to_ofp10(pp->supported);
2676     opp->peer = netdev_port_features_to_ofp10(pp->peer);
2677 }
2678
2679 static void
2680 ofputil_encode_ofp11_port(const struct ofputil_phy_port *pp,
2681                           struct ofp11_port *op)
2682 {
2683     memset(op, 0, sizeof *op);
2684
2685     op->port_no = ofputil_port_to_ofp11(pp->port_no);
2686     memcpy(op->hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2687     ovs_strlcpy(op->name, pp->name, OFP_MAX_PORT_NAME_LEN);
2688
2689     op->config = htonl(pp->config & OFPPC11_ALL);
2690     op->state = htonl(pp->state & OFPPS11_ALL);
2691
2692     op->curr = netdev_port_features_to_ofp11(pp->curr);
2693     op->advertised = netdev_port_features_to_ofp11(pp->advertised);
2694     op->supported = netdev_port_features_to_ofp11(pp->supported);
2695     op->peer = netdev_port_features_to_ofp11(pp->peer);
2696
2697     op->curr_speed = htonl(pp->curr_speed);
2698     op->max_speed = htonl(pp->max_speed);
2699 }
2700
2701 static void
2702 ofputil_put_phy_port(uint8_t ofp_version, const struct ofputil_phy_port *pp,
2703                      struct ofpbuf *b)
2704 {
2705     if (ofp_version == OFP10_VERSION) {
2706         struct ofp10_phy_port *opp;
2707         if (b->size + sizeof *opp <= UINT16_MAX) {
2708             opp = ofpbuf_put_uninit(b, sizeof *opp);
2709             ofputil_encode_ofp10_phy_port(pp, opp);
2710         }
2711     } else {
2712         struct ofp11_port *op;
2713         if (b->size + sizeof *op <= UINT16_MAX) {
2714             op = ofpbuf_put_uninit(b, sizeof *op);
2715             ofputil_encode_ofp11_port(pp, op);
2716         }
2717     }
2718 }
2719
2720 void
2721 ofputil_append_port_desc_stats_reply(uint8_t ofp_version,
2722                                      const struct ofputil_phy_port *pp,
2723                                      struct list *replies)
2724 {
2725     if (ofp_version == OFP10_VERSION) {
2726         struct ofp10_phy_port *opp;
2727
2728         opp = ofputil_append_stats_reply(sizeof *opp, replies);
2729         ofputil_encode_ofp10_phy_port(pp, opp);
2730     } else {
2731         struct ofp11_port *op;
2732
2733         op = ofputil_append_stats_reply(sizeof *op, replies);
2734         ofputil_encode_ofp11_port(pp, op);
2735     }
2736 }
2737 \f
2738 /* ofputil_switch_features */
2739
2740 #define OFPC_COMMON (OFPC_FLOW_STATS | OFPC_TABLE_STATS | OFPC_PORT_STATS | \
2741                      OFPC_IP_REASM | OFPC_QUEUE_STATS | OFPC_ARP_MATCH_IP)
2742 BUILD_ASSERT_DECL((int) OFPUTIL_C_FLOW_STATS == OFPC_FLOW_STATS);
2743 BUILD_ASSERT_DECL((int) OFPUTIL_C_TABLE_STATS == OFPC_TABLE_STATS);
2744 BUILD_ASSERT_DECL((int) OFPUTIL_C_PORT_STATS == OFPC_PORT_STATS);
2745 BUILD_ASSERT_DECL((int) OFPUTIL_C_IP_REASM == OFPC_IP_REASM);
2746 BUILD_ASSERT_DECL((int) OFPUTIL_C_QUEUE_STATS == OFPC_QUEUE_STATS);
2747 BUILD_ASSERT_DECL((int) OFPUTIL_C_ARP_MATCH_IP == OFPC_ARP_MATCH_IP);
2748
2749 struct ofputil_action_bit_translation {
2750     enum ofputil_action_bitmap ofputil_bit;
2751     int of_bit;
2752 };
2753
2754 static const struct ofputil_action_bit_translation of10_action_bits[] = {
2755     { OFPUTIL_A_OUTPUT,       OFPAT10_OUTPUT },
2756     { OFPUTIL_A_SET_VLAN_VID, OFPAT10_SET_VLAN_VID },
2757     { OFPUTIL_A_SET_VLAN_PCP, OFPAT10_SET_VLAN_PCP },
2758     { OFPUTIL_A_STRIP_VLAN,   OFPAT10_STRIP_VLAN },
2759     { OFPUTIL_A_SET_DL_SRC,   OFPAT10_SET_DL_SRC },
2760     { OFPUTIL_A_SET_DL_DST,   OFPAT10_SET_DL_DST },
2761     { OFPUTIL_A_SET_NW_SRC,   OFPAT10_SET_NW_SRC },
2762     { OFPUTIL_A_SET_NW_DST,   OFPAT10_SET_NW_DST },
2763     { OFPUTIL_A_SET_NW_TOS,   OFPAT10_SET_NW_TOS },
2764     { OFPUTIL_A_SET_TP_SRC,   OFPAT10_SET_TP_SRC },
2765     { OFPUTIL_A_SET_TP_DST,   OFPAT10_SET_TP_DST },
2766     { OFPUTIL_A_ENQUEUE,      OFPAT10_ENQUEUE },
2767     { 0, 0 },
2768 };
2769
2770 static const struct ofputil_action_bit_translation of11_action_bits[] = {
2771     { OFPUTIL_A_OUTPUT,         OFPAT11_OUTPUT },
2772     { OFPUTIL_A_SET_VLAN_VID,   OFPAT11_SET_VLAN_VID },
2773     { OFPUTIL_A_SET_VLAN_PCP,   OFPAT11_SET_VLAN_PCP },
2774     { OFPUTIL_A_SET_DL_SRC,     OFPAT11_SET_DL_SRC },
2775     { OFPUTIL_A_SET_DL_DST,     OFPAT11_SET_DL_DST },
2776     { OFPUTIL_A_SET_NW_SRC,     OFPAT11_SET_NW_SRC },
2777     { OFPUTIL_A_SET_NW_DST,     OFPAT11_SET_NW_DST },
2778     { OFPUTIL_A_SET_NW_TOS,     OFPAT11_SET_NW_TOS },
2779     { OFPUTIL_A_SET_NW_ECN,     OFPAT11_SET_NW_ECN },
2780     { OFPUTIL_A_SET_TP_SRC,     OFPAT11_SET_TP_SRC },
2781     { OFPUTIL_A_SET_TP_DST,     OFPAT11_SET_TP_DST },
2782     { OFPUTIL_A_COPY_TTL_OUT,   OFPAT11_COPY_TTL_OUT },
2783     { OFPUTIL_A_COPY_TTL_IN,    OFPAT11_COPY_TTL_IN },
2784     { OFPUTIL_A_SET_MPLS_LABEL, OFPAT11_SET_MPLS_LABEL },
2785     { OFPUTIL_A_SET_MPLS_TC,    OFPAT11_SET_MPLS_TC },
2786     { OFPUTIL_A_SET_MPLS_TTL,   OFPAT11_SET_MPLS_TTL },
2787     { OFPUTIL_A_DEC_MPLS_TTL,   OFPAT11_DEC_MPLS_TTL },
2788     { OFPUTIL_A_PUSH_VLAN,      OFPAT11_PUSH_VLAN },
2789     { OFPUTIL_A_POP_VLAN,       OFPAT11_POP_VLAN },
2790     { OFPUTIL_A_PUSH_MPLS,      OFPAT11_PUSH_MPLS },
2791     { OFPUTIL_A_POP_MPLS,       OFPAT11_POP_MPLS },
2792     { OFPUTIL_A_SET_QUEUE,      OFPAT11_SET_QUEUE },
2793     { OFPUTIL_A_GROUP,          OFPAT11_GROUP },
2794     { OFPUTIL_A_SET_NW_TTL,     OFPAT11_SET_NW_TTL },
2795     { OFPUTIL_A_DEC_NW_TTL,     OFPAT11_DEC_NW_TTL },
2796     { 0, 0 },
2797 };
2798
2799 static enum ofputil_action_bitmap
2800 decode_action_bits(ovs_be32 of_actions,
2801                    const struct ofputil_action_bit_translation *x)
2802 {
2803     enum ofputil_action_bitmap ofputil_actions;
2804
2805     ofputil_actions = 0;
2806     for (; x->ofputil_bit; x++) {
2807         if (of_actions & htonl(1u << x->of_bit)) {
2808             ofputil_actions |= x->ofputil_bit;
2809         }
2810     }
2811     return ofputil_actions;
2812 }
2813
2814 /* Decodes an OpenFlow 1.0 or 1.1 "switch_features" structure 'osf' into an
2815  * abstract representation in '*features'.  Initializes '*b' to iterate over
2816  * the OpenFlow port structures following 'osf' with later calls to
2817  * ofputil_pull_phy_port().  Returns 0 if successful, otherwise an
2818  * OFPERR_* value.  */
2819 enum ofperr
2820 ofputil_decode_switch_features(const struct ofp_switch_features *osf,
2821                                struct ofputil_switch_features *features,
2822                                struct ofpbuf *b)
2823 {
2824     ofpbuf_use_const(b, osf, ntohs(osf->header.length));
2825     ofpbuf_pull(b, sizeof *osf);
2826
2827     features->datapath_id = ntohll(osf->datapath_id);
2828     features->n_buffers = ntohl(osf->n_buffers);
2829     features->n_tables = osf->n_tables;
2830
2831     features->capabilities = ntohl(osf->capabilities) & OFPC_COMMON;
2832
2833     if (b->size % ofputil_get_phy_port_size(osf->header.version)) {
2834         return OFPERR_OFPBRC_BAD_LEN;
2835     }
2836
2837     if (osf->header.version == OFP10_VERSION) {
2838         if (osf->capabilities & htonl(OFPC10_STP)) {
2839             features->capabilities |= OFPUTIL_C_STP;
2840         }
2841         features->actions = decode_action_bits(osf->actions, of10_action_bits);
2842     } else if (osf->header.version == OFP11_VERSION) {
2843         if (osf->capabilities & htonl(OFPC11_GROUP_STATS)) {
2844             features->capabilities |= OFPUTIL_C_GROUP_STATS;
2845         }
2846         features->actions = decode_action_bits(osf->actions, of11_action_bits);
2847     } else {
2848         return OFPERR_OFPBRC_BAD_VERSION;
2849     }
2850
2851     return 0;
2852 }
2853
2854 /* Returns true if the maximum number of ports are in 'osf'. */
2855 static bool
2856 max_ports_in_features(const struct ofp_switch_features *osf)
2857 {
2858     size_t pp_size = ofputil_get_phy_port_size(osf->header.version);
2859     return ntohs(osf->header.length) + pp_size > UINT16_MAX;
2860 }
2861
2862 /* Given a buffer 'b' that contains a Features Reply message, checks if
2863  * it contains the maximum number of ports that will fit.  If so, it
2864  * returns true and removes the ports from the message.  The caller
2865  * should then send an OFPST_PORT_DESC stats request to get the ports,
2866  * since the switch may have more ports than could be represented in the
2867  * Features Reply.  Otherwise, returns false.
2868  */
2869 bool
2870 ofputil_switch_features_ports_trunc(struct ofpbuf *b)
2871 {
2872     struct ofp_switch_features *osf = b->data;
2873
2874     if (max_ports_in_features(osf)) {
2875         /* Remove all the ports. */
2876         b->size = sizeof(*osf);
2877         update_openflow_length(b);
2878
2879         return true;
2880     }
2881
2882     return false;
2883 }
2884
2885 static ovs_be32
2886 encode_action_bits(enum ofputil_action_bitmap ofputil_actions,
2887                    const struct ofputil_action_bit_translation *x)
2888 {
2889     uint32_t of_actions;
2890
2891     of_actions = 0;
2892     for (; x->ofputil_bit; x++) {
2893         if (ofputil_actions & x->ofputil_bit) {
2894             of_actions |= 1 << x->of_bit;
2895         }
2896     }
2897     return htonl(of_actions);
2898 }
2899
2900 /* Returns a buffer owned by the caller that encodes 'features' in the format
2901  * required by 'protocol' with the given 'xid'.  The caller should append port
2902  * information to the buffer with subsequent calls to
2903  * ofputil_put_switch_features_port(). */
2904 struct ofpbuf *
2905 ofputil_encode_switch_features(const struct ofputil_switch_features *features,
2906                                enum ofputil_protocol protocol, ovs_be32 xid)
2907 {
2908     struct ofp_switch_features *osf;
2909     struct ofpbuf *b;
2910
2911     osf = make_openflow_xid(sizeof *osf, OFPT_FEATURES_REPLY, xid, &b);
2912     osf->header.version = ofputil_protocol_to_ofp_version(protocol);
2913     osf->datapath_id = htonll(features->datapath_id);
2914     osf->n_buffers = htonl(features->n_buffers);
2915     osf->n_tables = features->n_tables;
2916
2917     osf->capabilities = htonl(features->capabilities & OFPC_COMMON);
2918     if (osf->header.version == OFP10_VERSION) {
2919         if (features->capabilities & OFPUTIL_C_STP) {
2920             osf->capabilities |= htonl(OFPC10_STP);
2921         }
2922         osf->actions = encode_action_bits(features->actions, of10_action_bits);
2923     } else {
2924         if (features->capabilities & OFPUTIL_C_GROUP_STATS) {
2925             osf->capabilities |= htonl(OFPC11_GROUP_STATS);
2926         }
2927         osf->actions = encode_action_bits(features->actions, of11_action_bits);
2928     }
2929
2930     return b;
2931 }
2932
2933 /* Encodes 'pp' into the format required by the switch_features message already
2934  * in 'b', which should have been returned by ofputil_encode_switch_features(),
2935  * and appends the encoded version to 'b'. */
2936 void
2937 ofputil_put_switch_features_port(const struct ofputil_phy_port *pp,
2938                                  struct ofpbuf *b)
2939 {
2940     const struct ofp_switch_features *osf = b->data;
2941
2942     ofputil_put_phy_port(osf->header.version, pp, b);
2943 }
2944 \f
2945 /* ofputil_port_status */
2946
2947 /* Decodes the OpenFlow "port status" message in '*ops' into an abstract form
2948  * in '*ps'.  Returns 0 if successful, otherwise an OFPERR_* value. */
2949 enum ofperr
2950 ofputil_decode_port_status(const struct ofp_port_status *ops,
2951                            struct ofputil_port_status *ps)
2952 {
2953     struct ofpbuf b;
2954     int retval;
2955
2956     if (ops->reason != OFPPR_ADD &&
2957         ops->reason != OFPPR_DELETE &&
2958         ops->reason != OFPPR_MODIFY) {
2959         return OFPERR_NXBRC_BAD_REASON;
2960     }
2961     ps->reason = ops->reason;
2962
2963     ofpbuf_use_const(&b, ops, ntohs(ops->header.length));
2964     ofpbuf_pull(&b, sizeof *ops);
2965     retval = ofputil_pull_phy_port(ops->header.version, &b, &ps->desc);
2966     assert(retval != EOF);
2967     return retval;
2968 }
2969
2970 /* Converts the abstract form of a "port status" message in '*ps' into an
2971  * OpenFlow message suitable for 'protocol', and returns that encoded form in
2972  * a buffer owned by the caller. */
2973 struct ofpbuf *
2974 ofputil_encode_port_status(const struct ofputil_port_status *ps,
2975                            enum ofputil_protocol protocol)
2976 {
2977     struct ofp_port_status *ops;
2978     struct ofpbuf *b;
2979
2980     b = ofpbuf_new(sizeof *ops + sizeof(struct ofp11_port));
2981     ops = put_openflow_xid(sizeof *ops, OFPT_PORT_STATUS, htonl(0), b);
2982     ops->header.version = ofputil_protocol_to_ofp_version(protocol);
2983     ops->reason = ps->reason;
2984     ofputil_put_phy_port(ops->header.version, &ps->desc, b);
2985     update_openflow_length(b);
2986     return b;
2987 }
2988 \f
2989 /* ofputil_port_mod */
2990
2991 /* Decodes the OpenFlow "port mod" message in '*oh' into an abstract form in
2992  * '*pm'.  Returns 0 if successful, otherwise an OFPERR_* value. */
2993 enum ofperr
2994 ofputil_decode_port_mod(const struct ofp_header *oh,
2995                         struct ofputil_port_mod *pm)
2996 {
2997     if (oh->version == OFP10_VERSION) {
2998         const struct ofp10_port_mod *opm = (const struct ofp10_port_mod *) oh;
2999
3000         if (oh->length != htons(sizeof *opm)) {
3001             return OFPERR_OFPBRC_BAD_LEN;
3002         }
3003
3004         pm->port_no = ntohs(opm->port_no);
3005         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
3006         pm->config = ntohl(opm->config) & OFPPC10_ALL;
3007         pm->mask = ntohl(opm->mask) & OFPPC10_ALL;
3008         pm->advertise = netdev_port_features_from_ofp10(opm->advertise);
3009     } else if (oh->version == OFP11_VERSION) {
3010         const struct ofp11_port_mod *opm = (const struct ofp11_port_mod *) oh;
3011         enum ofperr error;
3012
3013         if (oh->length != htons(sizeof *opm)) {
3014             return OFPERR_OFPBRC_BAD_LEN;
3015         }
3016
3017         error = ofputil_port_from_ofp11(opm->port_no, &pm->port_no);
3018         if (error) {
3019             return error;
3020         }
3021
3022         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
3023         pm->config = ntohl(opm->config) & OFPPC11_ALL;
3024         pm->mask = ntohl(opm->mask) & OFPPC11_ALL;
3025         pm->advertise = netdev_port_features_from_ofp11(opm->advertise);
3026     } else {
3027         return OFPERR_OFPBRC_BAD_VERSION;
3028     }
3029
3030     pm->config &= pm->mask;
3031     return 0;
3032 }
3033
3034 /* Converts the abstract form of a "port mod" message in '*pm' into an OpenFlow
3035  * message suitable for 'protocol', and returns that encoded form in a buffer
3036  * owned by the caller. */
3037 struct ofpbuf *
3038 ofputil_encode_port_mod(const struct ofputil_port_mod *pm,
3039                         enum ofputil_protocol protocol)
3040 {
3041     uint8_t ofp_version = ofputil_protocol_to_ofp_version(protocol);
3042     struct ofpbuf *b;
3043
3044     if (ofp_version == OFP10_VERSION) {
3045         struct ofp10_port_mod *opm;
3046
3047         opm = make_openflow(sizeof *opm, OFPT10_PORT_MOD, &b);
3048         opm->port_no = htons(pm->port_no);
3049         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
3050         opm->config = htonl(pm->config & OFPPC10_ALL);
3051         opm->mask = htonl(pm->mask & OFPPC10_ALL);
3052         opm->advertise = netdev_port_features_to_ofp10(pm->advertise);
3053     } else if (ofp_version == OFP11_VERSION) {
3054         struct ofp11_port_mod *opm;
3055
3056         opm = make_openflow(sizeof *opm, OFPT11_PORT_MOD, &b);
3057         opm->port_no = htonl(pm->port_no);
3058         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
3059         opm->config = htonl(pm->config & OFPPC11_ALL);
3060         opm->mask = htonl(pm->mask & OFPPC11_ALL);
3061         opm->advertise = netdev_port_features_to_ofp11(pm->advertise);
3062     } else {
3063         NOT_REACHED();
3064     }
3065
3066     return b;
3067 }
3068
3069 struct ofpbuf *
3070 ofputil_encode_packet_out(const struct ofputil_packet_out *po)
3071 {
3072     struct ofp_packet_out *opo;
3073     size_t actions_len;
3074     struct ofpbuf *msg;
3075     size_t size;
3076
3077     actions_len = po->n_actions * sizeof *po->actions;
3078     size = sizeof *opo + actions_len;
3079     if (po->buffer_id == UINT32_MAX) {
3080         size += po->packet_len;
3081     }
3082
3083     msg = ofpbuf_new(size);
3084     opo = put_openflow(sizeof *opo, OFPT_PACKET_OUT, msg);
3085     opo->buffer_id = htonl(po->buffer_id);
3086     opo->in_port = htons(po->in_port);
3087     opo->actions_len = htons(actions_len);
3088     ofpbuf_put(msg, po->actions, actions_len);
3089     if (po->buffer_id == UINT32_MAX) {
3090         ofpbuf_put(msg, po->packet, po->packet_len);
3091     }
3092     update_openflow_length(msg);
3093
3094     return msg;
3095 }
3096
3097 /* Returns a string representing the message type of 'type'.  The string is the
3098  * enumeration constant for the type, e.g. "OFPT_HELLO".  For statistics
3099  * messages, the constant is followed by "request" or "reply",
3100  * e.g. "OFPST_AGGREGATE reply". */
3101 const char *
3102 ofputil_msg_type_name(const struct ofputil_msg_type *type)
3103 {
3104     return type->name;
3105 }
3106 \f
3107 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
3108  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
3109  * an arbitrary transaction id.  Allocated bytes beyond the header, if any, are
3110  * zeroed.
3111  *
3112  * The caller is responsible for freeing '*bufferp' when it is no longer
3113  * needed.
3114  *
3115  * The OpenFlow header length is initially set to 'openflow_len'; if the
3116  * message is later extended, the length should be updated with
3117  * update_openflow_length() before sending.
3118  *
3119  * Returns the header. */
3120 void *
3121 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp)
3122 {
3123     *bufferp = ofpbuf_new(openflow_len);
3124     return put_openflow_xid(openflow_len, type, alloc_xid(), *bufferp);
3125 }
3126
3127 /* Similar to make_openflow() but creates a Nicira vendor extension message
3128  * with the specific 'subtype'.  'subtype' should be in host byte order. */
3129 void *
3130 make_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf **bufferp)
3131 {
3132     return make_nxmsg_xid(openflow_len, subtype, alloc_xid(), bufferp);
3133 }
3134
3135 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
3136  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
3137  * transaction id 'xid'.  Allocated bytes beyond the header, if any, are
3138  * zeroed.
3139  *
3140  * The caller is responsible for freeing '*bufferp' when it is no longer
3141  * needed.
3142  *
3143  * The OpenFlow header length is initially set to 'openflow_len'; if the
3144  * message is later extended, the length should be updated with
3145  * update_openflow_length() before sending.
3146  *
3147  * Returns the header. */
3148 void *
3149 make_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
3150                   struct ofpbuf **bufferp)
3151 {
3152     *bufferp = ofpbuf_new(openflow_len);
3153     return put_openflow_xid(openflow_len, type, xid, *bufferp);
3154 }
3155
3156 /* Similar to make_openflow_xid() but creates a Nicira vendor extension message
3157  * with the specific 'subtype'.  'subtype' should be in host byte order. */
3158 void *
3159 make_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
3160                struct ofpbuf **bufferp)
3161 {
3162     *bufferp = ofpbuf_new(openflow_len);
3163     return put_nxmsg_xid(openflow_len, subtype, xid, *bufferp);
3164 }
3165
3166 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
3167  * with the given 'type' and an arbitrary transaction id.  Allocated bytes
3168  * beyond the header, if any, are zeroed.
3169  *
3170  * The OpenFlow header length is initially set to 'openflow_len'; if the
3171  * message is later extended, the length should be updated with
3172  * update_openflow_length() before sending.
3173  *
3174  * Returns the header. */
3175 void *
3176 put_openflow(size_t openflow_len, uint8_t type, struct ofpbuf *buffer)
3177 {
3178     return put_openflow_xid(openflow_len, type, alloc_xid(), buffer);
3179 }
3180
3181 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
3182  * with the given 'type' and an transaction id 'xid'.  Allocated bytes beyond
3183  * the header, if any, are zeroed.
3184  *
3185  * The OpenFlow header length is initially set to 'openflow_len'; if the
3186  * message is later extended, the length should be updated with
3187  * update_openflow_length() before sending.
3188  *
3189  * Returns the header. */
3190 void *
3191 put_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
3192                  struct ofpbuf *buffer)
3193 {
3194     struct ofp_header *oh;
3195
3196     assert(openflow_len >= sizeof *oh);
3197     assert(openflow_len <= UINT16_MAX);
3198
3199     oh = ofpbuf_put_uninit(buffer, openflow_len);
3200     oh->version = OFP10_VERSION;
3201     oh->type = type;
3202     oh->length = htons(openflow_len);
3203     oh->xid = xid;
3204     memset(oh + 1, 0, openflow_len - sizeof *oh);
3205     return oh;
3206 }
3207
3208 /* Similar to put_openflow() but append a Nicira vendor extension message with
3209  * the specific 'subtype'.  'subtype' should be in host byte order. */
3210 void *
3211 put_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf *buffer)
3212 {
3213     return put_nxmsg_xid(openflow_len, subtype, alloc_xid(), buffer);
3214 }
3215
3216 /* Similar to put_openflow_xid() but append a Nicira vendor extension message
3217  * with the specific 'subtype'.  'subtype' should be in host byte order. */
3218 void *
3219 put_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
3220               struct ofpbuf *buffer)
3221 {
3222     struct nicira_header *nxh;
3223
3224     nxh = put_openflow_xid(openflow_len, OFPT_VENDOR, xid, buffer);
3225     nxh->vendor = htonl(NX_VENDOR_ID);
3226     nxh->subtype = htonl(subtype);
3227     return nxh;
3228 }
3229
3230 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
3231  * 'buffer->size'. */
3232 void
3233 update_openflow_length(struct ofpbuf *buffer)
3234 {
3235     struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
3236     oh->length = htons(buffer->size);
3237 }
3238
3239 static void
3240 put_stats__(ovs_be32 xid, uint8_t ofp_type,
3241             ovs_be16 ofpst_type, ovs_be32 nxst_subtype,
3242             struct ofpbuf *msg)
3243 {
3244     if (ofpst_type == htons(OFPST_VENDOR)) {
3245         struct nicira_stats_msg *nsm;
3246
3247         nsm = put_openflow_xid(sizeof *nsm, ofp_type, xid, msg);
3248         nsm->vsm.osm.type = ofpst_type;
3249         nsm->vsm.vendor = htonl(NX_VENDOR_ID);
3250         nsm->subtype = nxst_subtype;
3251     } else {
3252         struct ofp_stats_msg *osm;
3253
3254         osm = put_openflow_xid(sizeof *osm, ofp_type, xid, msg);
3255         osm->type = ofpst_type;
3256     }
3257 }
3258
3259 /* Creates a statistics request message with total length 'openflow_len'
3260  * (including all headers) and the given 'ofpst_type', and stores the buffer
3261  * containing the new message in '*bufferp'.  If 'ofpst_type' is OFPST_VENDOR
3262  * then 'nxst_subtype' is used as the Nicira vendor extension statistics
3263  * subtype (otherwise 'nxst_subtype' is ignored).
3264  *
3265  * Initializes bytes following the headers to all-bits-zero.
3266  *
3267  * Returns the first byte of the new message. */
3268 void *
3269 ofputil_make_stats_request(size_t openflow_len, uint16_t ofpst_type,
3270                            uint32_t nxst_subtype, struct ofpbuf **bufferp)
3271 {
3272     struct ofpbuf *msg;
3273
3274     msg = *bufferp = ofpbuf_new(openflow_len);
3275     put_stats__(alloc_xid(), OFPT10_STATS_REQUEST,
3276                 htons(ofpst_type), htonl(nxst_subtype), msg);
3277     ofpbuf_padto(msg, openflow_len);
3278
3279     return msg->data;
3280 }
3281
3282 static void
3283 put_stats_reply__(const struct ofp_stats_msg *request, struct ofpbuf *msg)
3284 {
3285     assert(request->header.type == OFPT10_STATS_REQUEST ||
3286            request->header.type == OFPT10_STATS_REPLY);
3287     put_stats__(request->header.xid, OFPT10_STATS_REPLY, request->type,
3288                 (request->type != htons(OFPST_VENDOR)
3289                  ? htonl(0)
3290                  : ((const struct nicira_stats_msg *) request)->subtype),
3291                 msg);
3292 }
3293
3294 /* Creates a statistics reply message with total length 'openflow_len'
3295  * (including all headers) and the same type (either a standard OpenFlow
3296  * statistics type or a Nicira extension type and subtype) as 'request', and
3297  * stores the buffer containing the new message in '*bufferp'.
3298  *
3299  * Initializes bytes following the headers to all-bits-zero.
3300  *
3301  * Returns the first byte of the new message. */
3302 void *
3303 ofputil_make_stats_reply(size_t openflow_len,
3304                          const struct ofp_stats_msg *request,
3305                          struct ofpbuf **bufferp)
3306 {
3307     struct ofpbuf *msg;
3308
3309     msg = *bufferp = ofpbuf_new(openflow_len);
3310     put_stats_reply__(request, msg);
3311     ofpbuf_padto(msg, openflow_len);
3312
3313     return msg->data;
3314 }
3315
3316 /* Initializes 'replies' as a list of ofpbufs that will contain a series of
3317  * replies to 'request', which should be an OpenFlow or Nicira extension
3318  * statistics request.  Initially 'replies' will have a single reply message
3319  * that has only a header.  The functions ofputil_reserve_stats_reply() and
3320  * ofputil_append_stats_reply() may be used to add to the reply. */
3321 void
3322 ofputil_start_stats_reply(const struct ofp_stats_msg *request,
3323                           struct list *replies)
3324 {
3325     struct ofpbuf *msg;
3326
3327     msg = ofpbuf_new(1024);
3328     put_stats_reply__(request, msg);
3329
3330     list_init(replies);
3331     list_push_back(replies, &msg->list_node);
3332 }
3333
3334 /* Prepares to append up to 'len' bytes to the series of statistics replies in
3335  * 'replies', which should have been initialized with
3336  * ofputil_start_stats_reply().  Returns an ofpbuf with at least 'len' bytes of
3337  * tailroom.  (The 'len' bytes have not actually be allocated; the caller must
3338  * do so with e.g. ofpbuf_put_uninit().) */
3339 struct ofpbuf *
3340 ofputil_reserve_stats_reply(size_t len, struct list *replies)
3341 {
3342     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
3343     struct ofp_stats_msg *osm = msg->data;
3344
3345     if (msg->size + len <= UINT16_MAX) {
3346         ofpbuf_prealloc_tailroom(msg, len);
3347     } else {
3348         osm->flags |= htons(OFPSF_REPLY_MORE);
3349
3350         msg = ofpbuf_new(MAX(1024, sizeof(struct nicira_stats_msg) + len));
3351         put_stats_reply__(osm, msg);
3352         list_push_back(replies, &msg->list_node);
3353     }
3354     return msg;
3355 }
3356
3357 /* Appends 'len' bytes to the series of statistics replies in 'replies', and
3358  * returns the first byte. */
3359 void *
3360 ofputil_append_stats_reply(size_t len, struct list *replies)
3361 {
3362     return ofpbuf_put_uninit(ofputil_reserve_stats_reply(len, replies), len);
3363 }
3364
3365 /* Returns the first byte past the ofp_stats_msg header in 'oh'. */
3366 const void *
3367 ofputil_stats_body(const struct ofp_header *oh)
3368 {
3369     assert(oh->type == OFPT10_STATS_REQUEST || oh->type == OFPT10_STATS_REPLY);
3370     return (const struct ofp_stats_msg *) oh + 1;
3371 }
3372
3373 /* Returns the number of bytes past the ofp_stats_msg header in 'oh'. */
3374 size_t
3375 ofputil_stats_body_len(const struct ofp_header *oh)
3376 {
3377     assert(oh->type == OFPT10_STATS_REQUEST || oh->type == OFPT10_STATS_REPLY);
3378     return ntohs(oh->length) - sizeof(struct ofp_stats_msg);
3379 }
3380
3381 /* Returns the first byte past the nicira_stats_msg header in 'oh'. */
3382 const void *
3383 ofputil_nxstats_body(const struct ofp_header *oh)
3384 {
3385     assert(oh->type == OFPT10_STATS_REQUEST || oh->type == OFPT10_STATS_REPLY);
3386     return ((const struct nicira_stats_msg *) oh) + 1;
3387 }
3388
3389 /* Returns the number of bytes past the nicira_stats_msg header in 'oh'. */
3390 size_t
3391 ofputil_nxstats_body_len(const struct ofp_header *oh)
3392 {
3393     assert(oh->type == OFPT10_STATS_REQUEST || oh->type == OFPT10_STATS_REPLY);
3394     return ntohs(oh->length) - sizeof(struct nicira_stats_msg);
3395 }
3396
3397 struct ofpbuf *
3398 make_flow_mod(uint16_t command, const struct cls_rule *rule,
3399               size_t actions_len)
3400 {
3401     struct ofp_flow_mod *ofm;
3402     size_t size = sizeof *ofm + actions_len;
3403     struct ofpbuf *out = ofpbuf_new(size);
3404     ofm = ofpbuf_put_zeros(out, sizeof *ofm);
3405     ofm->header.version = OFP10_VERSION;
3406     ofm->header.type = OFPT_FLOW_MOD;
3407     ofm->header.length = htons(size);
3408     ofm->cookie = 0;
3409     ofm->priority = htons(MIN(rule->priority, UINT16_MAX));
3410     ofputil_cls_rule_to_ofp10_match(rule, &ofm->match);
3411     ofm->command = htons(command);
3412     return out;
3413 }
3414
3415 struct ofpbuf *
3416 make_add_flow(const struct cls_rule *rule, uint32_t buffer_id,
3417               uint16_t idle_timeout, size_t actions_len)
3418 {
3419     struct ofpbuf *out = make_flow_mod(OFPFC_ADD, rule, actions_len);
3420     struct ofp_flow_mod *ofm = out->data;
3421     ofm->idle_timeout = htons(idle_timeout);
3422     ofm->hard_timeout = htons(OFP_FLOW_PERMANENT);
3423     ofm->buffer_id = htonl(buffer_id);
3424     return out;
3425 }
3426
3427 struct ofpbuf *
3428 make_packet_in(uint32_t buffer_id, uint16_t in_port, uint8_t reason,
3429                const struct ofpbuf *payload, int max_send_len)
3430 {
3431     struct ofp_packet_in *opi;
3432     struct ofpbuf *buf;
3433     int send_len;
3434
3435     send_len = MIN(max_send_len, payload->size);
3436     buf = ofpbuf_new(sizeof *opi + send_len);
3437     opi = put_openflow_xid(offsetof(struct ofp_packet_in, data),
3438                            OFPT_PACKET_IN, 0, buf);
3439     opi->buffer_id = htonl(buffer_id);
3440     opi->total_len = htons(payload->size);
3441     opi->in_port = htons(in_port);
3442     opi->reason = reason;
3443     ofpbuf_put(buf, payload->data, send_len);
3444     update_openflow_length(buf);
3445
3446     return buf;
3447 }
3448
3449 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
3450 struct ofpbuf *
3451 make_echo_request(void)
3452 {
3453     struct ofp_header *rq;
3454     struct ofpbuf *out = ofpbuf_new(sizeof *rq);
3455     rq = ofpbuf_put_uninit(out, sizeof *rq);
3456     rq->version = OFP10_VERSION;
3457     rq->type = OFPT_ECHO_REQUEST;
3458     rq->length = htons(sizeof *rq);
3459     rq->xid = htonl(0);
3460     return out;
3461 }
3462
3463 /* Creates and returns an OFPT_ECHO_REPLY message matching the
3464  * OFPT_ECHO_REQUEST message in 'rq'. */
3465 struct ofpbuf *
3466 make_echo_reply(const struct ofp_header *rq)
3467 {
3468     size_t size = ntohs(rq->length);
3469     struct ofpbuf *out = ofpbuf_new(size);
3470     struct ofp_header *reply = ofpbuf_put(out, rq, size);
3471     reply->type = OFPT_ECHO_REPLY;
3472     return out;
3473 }
3474
3475 struct ofpbuf *
3476 ofputil_encode_barrier_request(void)
3477 {
3478     struct ofpbuf *msg;
3479
3480     make_openflow(sizeof(struct ofp_header), OFPT10_BARRIER_REQUEST, &msg);
3481     return msg;
3482 }
3483
3484 const char *
3485 ofputil_frag_handling_to_string(enum ofp_config_flags flags)
3486 {
3487     switch (flags & OFPC_FRAG_MASK) {
3488     case OFPC_FRAG_NORMAL:   return "normal";
3489     case OFPC_FRAG_DROP:     return "drop";
3490     case OFPC_FRAG_REASM:    return "reassemble";
3491     case OFPC_FRAG_NX_MATCH: return "nx-match";
3492     }
3493
3494     NOT_REACHED();
3495 }
3496
3497 bool
3498 ofputil_frag_handling_from_string(const char *s, enum ofp_config_flags *flags)
3499 {
3500     if (!strcasecmp(s, "normal")) {
3501         *flags = OFPC_FRAG_NORMAL;
3502     } else if (!strcasecmp(s, "drop")) {
3503         *flags = OFPC_FRAG_DROP;
3504     } else if (!strcasecmp(s, "reassemble")) {
3505         *flags = OFPC_FRAG_REASM;
3506     } else if (!strcasecmp(s, "nx-match")) {
3507         *flags = OFPC_FRAG_NX_MATCH;
3508     } else {
3509         return false;
3510     }
3511     return true;
3512 }
3513
3514 /* Converts the OpenFlow 1.1+ port number 'ofp11_port' into an OpenFlow 1.0
3515  * port number and stores the latter in '*ofp10_port', for the purpose of
3516  * decoding OpenFlow 1.1+ protocol messages.  Returns 0 if successful,
3517  * otherwise an OFPERR_* number.
3518  *
3519  * See the definition of OFP11_MAX for an explanation of the mapping. */
3520 enum ofperr
3521 ofputil_port_from_ofp11(ovs_be32 ofp11_port, uint16_t *ofp10_port)
3522 {
3523     uint32_t ofp11_port_h = ntohl(ofp11_port);
3524
3525     if (ofp11_port_h < OFPP_MAX) {
3526         *ofp10_port = ofp11_port_h;
3527         return 0;
3528     } else if (ofp11_port_h >= OFPP11_MAX) {
3529         *ofp10_port = ofp11_port_h - OFPP11_OFFSET;
3530         return 0;
3531     } else {
3532         VLOG_WARN_RL(&bad_ofmsg_rl, "port %"PRIu32" is outside the supported "
3533                      "range 0 through %d or 0x%"PRIx32" through 0x%"PRIx32,
3534                      ofp11_port_h, OFPP_MAX - 1,
3535                      (uint32_t) OFPP11_MAX, UINT32_MAX);
3536         return OFPERR_OFPBAC_BAD_OUT_PORT;
3537     }
3538 }
3539
3540 /* Returns the OpenFlow 1.1+ port number equivalent to the OpenFlow 1.0 port
3541  * number 'ofp10_port', for encoding OpenFlow 1.1+ protocol messages.
3542  *
3543  * See the definition of OFP11_MAX for an explanation of the mapping. */
3544 ovs_be32
3545 ofputil_port_to_ofp11(uint16_t ofp10_port)
3546 {
3547     return htonl(ofp10_port < OFPP_MAX
3548                  ? ofp10_port
3549                  : ofp10_port + OFPP11_OFFSET);
3550 }
3551
3552 /* Checks that 'port' is a valid output port for the OFPAT10_OUTPUT action, given
3553  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
3554  * 'port' is valid, otherwise an OpenFlow return code. */
3555 enum ofperr
3556 ofputil_check_output_port(uint16_t port, int max_ports)
3557 {
3558     switch (port) {
3559     case OFPP_IN_PORT:
3560     case OFPP_TABLE:
3561     case OFPP_NORMAL:
3562     case OFPP_FLOOD:
3563     case OFPP_ALL:
3564     case OFPP_CONTROLLER:
3565     case OFPP_NONE:
3566     case OFPP_LOCAL:
3567         return 0;
3568
3569     default:
3570         if (port < max_ports) {
3571             return 0;
3572         }
3573         return OFPERR_OFPBAC_BAD_OUT_PORT;
3574     }
3575 }
3576
3577 #define OFPUTIL_NAMED_PORTS                     \
3578         OFPUTIL_NAMED_PORT(IN_PORT)             \
3579         OFPUTIL_NAMED_PORT(TABLE)               \
3580         OFPUTIL_NAMED_PORT(NORMAL)              \
3581         OFPUTIL_NAMED_PORT(FLOOD)               \
3582         OFPUTIL_NAMED_PORT(ALL)                 \
3583         OFPUTIL_NAMED_PORT(CONTROLLER)          \
3584         OFPUTIL_NAMED_PORT(LOCAL)               \
3585         OFPUTIL_NAMED_PORT(NONE)
3586
3587 /* Checks whether 's' is the string representation of an OpenFlow port number,
3588  * either as an integer or a string name (e.g. "LOCAL").  If it is, stores the
3589  * number in '*port' and returns true.  Otherwise, returns false. */
3590 bool
3591 ofputil_port_from_string(const char *name, uint16_t *port)
3592 {
3593     struct pair {
3594         const char *name;
3595         uint16_t value;
3596     };
3597     static const struct pair pairs[] = {
3598 #define OFPUTIL_NAMED_PORT(NAME) {#NAME, OFPP_##NAME},
3599         OFPUTIL_NAMED_PORTS
3600 #undef OFPUTIL_NAMED_PORT
3601     };
3602     static const int n_pairs = ARRAY_SIZE(pairs);
3603     int i;
3604
3605     if (str_to_int(name, 0, &i) && i >= 0 && i < UINT16_MAX) {
3606         *port = i;
3607         return true;
3608     }
3609
3610     for (i = 0; i < n_pairs; i++) {
3611         if (!strcasecmp(name, pairs[i].name)) {
3612             *port = pairs[i].value;
3613             return true;
3614         }
3615     }
3616     return false;
3617 }
3618
3619 /* Appends to 's' a string representation of the OpenFlow port number 'port'.
3620  * Most ports' string representation is just the port number, but for special
3621  * ports, e.g. OFPP_LOCAL, it is the name, e.g. "LOCAL". */
3622 void
3623 ofputil_format_port(uint16_t port, struct ds *s)
3624 {
3625     const char *name;
3626
3627     switch (port) {
3628 #define OFPUTIL_NAMED_PORT(NAME) case OFPP_##NAME: name = #NAME; break;
3629         OFPUTIL_NAMED_PORTS
3630 #undef OFPUTIL_NAMED_PORT
3631
3632     default:
3633         ds_put_format(s, "%"PRIu16, port);
3634         return;
3635     }
3636     ds_put_cstr(s, name);
3637 }
3638
3639 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
3640  * 'ofp_version', tries to pull the first element from the array.  If
3641  * successful, initializes '*pp' with an abstract representation of the
3642  * port and returns 0.  If no ports remain to be decoded, returns EOF.
3643  * On an error, returns a positive OFPERR_* value. */
3644 int
3645 ofputil_pull_phy_port(uint8_t ofp_version, struct ofpbuf *b,
3646                       struct ofputil_phy_port *pp)
3647 {
3648     if (ofp_version == OFP10_VERSION) {
3649         const struct ofp10_phy_port *opp = ofpbuf_try_pull(b, sizeof *opp);
3650         return opp ? ofputil_decode_ofp10_phy_port(pp, opp) : EOF;
3651     } else {
3652         const struct ofp11_port *op = ofpbuf_try_pull(b, sizeof *op);
3653         return op ? ofputil_decode_ofp11_port(pp, op) : EOF;
3654     }
3655 }
3656
3657 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
3658  * 'ofp_version', returns the number of elements. */
3659 size_t ofputil_count_phy_ports(uint8_t ofp_version, struct ofpbuf *b)
3660 {
3661     return b->size / ofputil_get_phy_port_size(ofp_version);
3662 }
3663
3664 static enum ofperr
3665 check_resubmit_table(const struct nx_action_resubmit *nar)
3666 {
3667     if (nar->pad[0] || nar->pad[1] || nar->pad[2]) {
3668         return OFPERR_OFPBAC_BAD_ARGUMENT;
3669     }
3670     return 0;
3671 }
3672
3673 static enum ofperr
3674 check_output_reg(const struct nx_action_output_reg *naor,
3675                  const struct flow *flow)
3676 {
3677     struct mf_subfield src;
3678     size_t i;
3679
3680     for (i = 0; i < sizeof naor->zero; i++) {
3681         if (naor->zero[i]) {
3682             return OFPERR_OFPBAC_BAD_ARGUMENT;
3683         }
3684     }
3685
3686     nxm_decode(&src, naor->src, naor->ofs_nbits);
3687     return mf_check_src(&src, flow);
3688 }
3689
3690 enum ofperr
3691 validate_actions(const union ofp_action *actions, size_t n_actions,
3692                  const struct flow *flow, int max_ports)
3693 {
3694     const union ofp_action *a;
3695     size_t left;
3696
3697     OFPUTIL_ACTION_FOR_EACH (a, left, actions, n_actions) {
3698         enum ofperr error;
3699         uint16_t port;
3700         int code;
3701
3702         code = ofputil_decode_action(a);
3703         if (code < 0) {
3704             error = -code;
3705             VLOG_WARN_RL(&bad_ofmsg_rl,
3706                          "action decoding error at offset %td (%s)",
3707                          (a - actions) * sizeof *a, ofperr_get_name(error));
3708
3709             return error;
3710         }
3711
3712         error = 0;
3713         switch ((enum ofputil_action_code) code) {
3714         case OFPUTIL_ACTION_INVALID:
3715             NOT_REACHED();
3716
3717         case OFPUTIL_OFPAT10_OUTPUT:
3718             error = ofputil_check_output_port(ntohs(a->output.port),
3719                                               max_ports);
3720             break;
3721
3722         case OFPUTIL_OFPAT10_SET_VLAN_VID:
3723             if (a->vlan_vid.vlan_vid & ~htons(0xfff)) {
3724                 error = OFPERR_OFPBAC_BAD_ARGUMENT;
3725             }
3726             break;
3727
3728         case OFPUTIL_OFPAT10_SET_VLAN_PCP:
3729             if (a->vlan_pcp.vlan_pcp & ~7) {
3730                 error = OFPERR_OFPBAC_BAD_ARGUMENT;
3731             }
3732             break;
3733
3734         case OFPUTIL_OFPAT10_ENQUEUE:
3735             port = ntohs(((const struct ofp_action_enqueue *) a)->port);
3736             if (port >= max_ports && port != OFPP_IN_PORT
3737                 && port != OFPP_LOCAL) {
3738                 error = OFPERR_OFPBAC_BAD_OUT_PORT;
3739             }
3740             break;
3741
3742         case OFPUTIL_NXAST_REG_MOVE:
3743             error = nxm_check_reg_move((const struct nx_action_reg_move *) a,
3744                                        flow);
3745             break;
3746
3747         case OFPUTIL_NXAST_REG_LOAD:
3748             error = nxm_check_reg_load((const struct nx_action_reg_load *) a,
3749                                        flow);
3750             break;
3751
3752         case OFPUTIL_NXAST_MULTIPATH:
3753             error = multipath_check((const struct nx_action_multipath *) a,
3754                                     flow);
3755             break;
3756
3757         case OFPUTIL_NXAST_AUTOPATH:
3758             error = autopath_check((const struct nx_action_autopath *) a,
3759                                    flow);
3760             break;
3761
3762         case OFPUTIL_NXAST_BUNDLE:
3763         case OFPUTIL_NXAST_BUNDLE_LOAD:
3764             error = bundle_check((const struct nx_action_bundle *) a,
3765                                  max_ports, flow);
3766             break;
3767
3768         case OFPUTIL_NXAST_OUTPUT_REG:
3769             error = check_output_reg((const struct nx_action_output_reg *) a,
3770                                      flow);
3771             break;
3772
3773         case OFPUTIL_NXAST_RESUBMIT_TABLE:
3774             error = check_resubmit_table(
3775                 (const struct nx_action_resubmit *) a);
3776             break;
3777
3778         case OFPUTIL_NXAST_LEARN:
3779             error = learn_check((const struct nx_action_learn *) a, flow);
3780             break;
3781
3782         case OFPUTIL_NXAST_CONTROLLER:
3783             if (((const struct nx_action_controller *) a)->zero) {
3784                 error = OFPERR_NXBAC_MUST_BE_ZERO;
3785             }
3786             break;
3787
3788         case OFPUTIL_OFPAT10_STRIP_VLAN:
3789         case OFPUTIL_OFPAT10_SET_NW_SRC:
3790         case OFPUTIL_OFPAT10_SET_NW_DST:
3791         case OFPUTIL_OFPAT10_SET_NW_TOS:
3792         case OFPUTIL_OFPAT10_SET_TP_SRC:
3793         case OFPUTIL_OFPAT10_SET_TP_DST:
3794         case OFPUTIL_OFPAT10_SET_DL_SRC:
3795         case OFPUTIL_OFPAT10_SET_DL_DST:
3796         case OFPUTIL_NXAST_RESUBMIT:
3797         case OFPUTIL_NXAST_SET_TUNNEL:
3798         case OFPUTIL_NXAST_SET_QUEUE:
3799         case OFPUTIL_NXAST_POP_QUEUE:
3800         case OFPUTIL_NXAST_NOTE:
3801         case OFPUTIL_NXAST_SET_TUNNEL64:
3802         case OFPUTIL_NXAST_EXIT:
3803         case OFPUTIL_NXAST_DEC_TTL:
3804         case OFPUTIL_NXAST_FIN_TIMEOUT:
3805             break;
3806         }
3807
3808         if (error) {
3809             VLOG_WARN_RL(&bad_ofmsg_rl, "bad action at offset %td (%s)",
3810                          (a - actions) * sizeof *a, ofperr_get_name(error));
3811             return error;
3812         }
3813     }
3814     if (left) {
3815         VLOG_WARN_RL(&bad_ofmsg_rl, "bad action format at offset %zu",
3816                      (n_actions - left) * sizeof *a);
3817         return OFPERR_OFPBAC_BAD_LEN;
3818     }
3819     return 0;
3820 }
3821
3822 struct ofputil_action {
3823     int code;
3824     unsigned int min_len;
3825     unsigned int max_len;
3826 };
3827
3828 static const struct ofputil_action action_bad_type
3829     = { -OFPERR_OFPBAC_BAD_TYPE,   0, UINT_MAX };
3830 static const struct ofputil_action action_bad_len
3831     = { -OFPERR_OFPBAC_BAD_LEN,    0, UINT_MAX };
3832 static const struct ofputil_action action_bad_vendor
3833     = { -OFPERR_OFPBAC_BAD_VENDOR, 0, UINT_MAX };
3834
3835 static const struct ofputil_action *
3836 ofputil_decode_ofpat_action(const union ofp_action *a)
3837 {
3838     enum ofp10_action_type type = ntohs(a->type);
3839
3840     switch (type) {
3841 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                    \
3842         case ENUM: {                                        \
3843             static const struct ofputil_action action = {   \
3844                 OFPUTIL_##ENUM,                             \
3845                 sizeof(struct STRUCT),                      \
3846                 sizeof(struct STRUCT)                       \
3847             };                                              \
3848             return &action;                                 \
3849         }
3850 #include "ofp-util.def"
3851
3852     case OFPAT10_VENDOR:
3853     default:
3854         return &action_bad_type;
3855     }
3856 }
3857
3858 static const struct ofputil_action *
3859 ofputil_decode_nxast_action(const union ofp_action *a)
3860 {
3861     const struct nx_action_header *nah = (const struct nx_action_header *) a;
3862     enum nx_action_subtype subtype = ntohs(nah->subtype);
3863
3864     switch (subtype) {
3865 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)            \
3866         case ENUM: {                                            \
3867             static const struct ofputil_action action = {       \
3868                 OFPUTIL_##ENUM,                                 \
3869                 sizeof(struct STRUCT),                          \
3870                 EXTENSIBLE ? UINT_MAX : sizeof(struct STRUCT)   \
3871             };                                                  \
3872             return &action;                                     \
3873         }
3874 #include "ofp-util.def"
3875
3876     case NXAST_SNAT__OBSOLETE:
3877     case NXAST_DROP_SPOOFED_ARP__OBSOLETE:
3878     default:
3879         return &action_bad_type;
3880     }
3881 }
3882
3883 /* Parses 'a' to determine its type.  Returns a nonnegative OFPUTIL_OFPAT10_* or
3884  * OFPUTIL_NXAST_* constant if successful, otherwise a negative OFPERR_* error
3885  * code.
3886  *
3887  * The caller must have already verified that 'a''s length is correct (that is,
3888  * a->header.len is nonzero and a multiple of sizeof(union ofp_action) and no
3889  * longer than the amount of space allocated to 'a').
3890  *
3891  * This function verifies that 'a''s length is correct for the type of action
3892  * that it represents. */
3893 int
3894 ofputil_decode_action(const union ofp_action *a)
3895 {
3896     const struct ofputil_action *action;
3897     uint16_t len = ntohs(a->header.len);
3898
3899     if (a->type != htons(OFPAT10_VENDOR)) {
3900         action = ofputil_decode_ofpat_action(a);
3901     } else {
3902         switch (ntohl(a->vendor.vendor)) {
3903         case NX_VENDOR_ID:
3904             if (len < sizeof(struct nx_action_header)) {
3905                 return -OFPERR_OFPBAC_BAD_LEN;
3906             }
3907             action = ofputil_decode_nxast_action(a);
3908             break;
3909         default:
3910             action = &action_bad_vendor;
3911             break;
3912         }
3913     }
3914
3915     return (len >= action->min_len && len <= action->max_len
3916             ? action->code
3917             : -OFPERR_OFPBAC_BAD_LEN);
3918 }
3919
3920 /* Parses 'a' and returns its type as an OFPUTIL_OFPAT10_* or OFPUTIL_NXAST_*
3921  * constant.  The caller must have already validated that 'a' is a valid action
3922  * understood by Open vSwitch (e.g. by a previous successful call to
3923  * ofputil_decode_action()). */
3924 enum ofputil_action_code
3925 ofputil_decode_action_unsafe(const union ofp_action *a)
3926 {
3927     const struct ofputil_action *action;
3928
3929     if (a->type != htons(OFPAT10_VENDOR)) {
3930         action = ofputil_decode_ofpat_action(a);
3931     } else {
3932         action = ofputil_decode_nxast_action(a);
3933     }
3934
3935     return action->code;
3936 }
3937
3938 /* Returns the 'enum ofputil_action_code' corresponding to 'name' (e.g. if
3939  * 'name' is "output" then the return value is OFPUTIL_OFPAT10_OUTPUT), or -1 if
3940  * 'name' is not the name of any action.
3941  *
3942  * ofp-util.def lists the mapping from names to action. */
3943 int
3944 ofputil_action_code_from_name(const char *name)
3945 {
3946     static const char *names[OFPUTIL_N_ACTIONS] = {
3947         NULL,
3948 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)             NAME,
3949 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) NAME,
3950 #include "ofp-util.def"
3951     };
3952
3953     const char **p;
3954
3955     for (p = names; p < &names[ARRAY_SIZE(names)]; p++) {
3956         if (*p && !strcasecmp(name, *p)) {
3957             return p - names;
3958         }
3959     }
3960     return -1;
3961 }
3962
3963 /* Appends an action of the type specified by 'code' to 'buf' and returns the
3964  * action.  Initializes the parts of 'action' that identify it as having type
3965  * <ENUM> and length 'sizeof *action' and zeros the rest.  For actions that
3966  * have variable length, the length used and cleared is that of struct
3967  * <STRUCT>.  */
3968 void *
3969 ofputil_put_action(enum ofputil_action_code code, struct ofpbuf *buf)
3970 {
3971     switch (code) {
3972     case OFPUTIL_ACTION_INVALID:
3973         NOT_REACHED();
3974
3975 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                    \
3976     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
3977 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)        \
3978     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
3979 #include "ofp-util.def"
3980     }
3981     NOT_REACHED();
3982 }
3983
3984 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                        \
3985     void                                                        \
3986     ofputil_init_##ENUM(struct STRUCT *s)                       \
3987     {                                                           \
3988         memset(s, 0, sizeof *s);                                \
3989         s->type = htons(ENUM);                                  \
3990         s->len = htons(sizeof *s);                              \
3991     }                                                           \
3992                                                                 \
3993     struct STRUCT *                                             \
3994     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
3995     {                                                           \
3996         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
3997         ofputil_init_##ENUM(s);                                 \
3998         return s;                                               \
3999     }
4000 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)            \
4001     void                                                        \
4002     ofputil_init_##ENUM(struct STRUCT *s)                       \
4003     {                                                           \
4004         memset(s, 0, sizeof *s);                                \
4005         s->type = htons(OFPAT10_VENDOR);                        \
4006         s->len = htons(sizeof *s);                              \
4007         s->vendor = htonl(NX_VENDOR_ID);                        \
4008         s->subtype = htons(ENUM);                               \
4009     }                                                           \
4010                                                                 \
4011     struct STRUCT *                                             \
4012     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
4013     {                                                           \
4014         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
4015         ofputil_init_##ENUM(s);                                 \
4016         return s;                                               \
4017     }
4018 #include "ofp-util.def"
4019
4020 /* Returns true if 'action' outputs to 'port', false otherwise. */
4021 bool
4022 action_outputs_to_port(const union ofp_action *action, ovs_be16 port)
4023 {
4024     switch (ofputil_decode_action(action)) {
4025     case OFPUTIL_OFPAT10_OUTPUT:
4026         return action->output.port == port;
4027     case OFPUTIL_OFPAT10_ENQUEUE:
4028         return ((const struct ofp_action_enqueue *) action)->port == port;
4029     case OFPUTIL_NXAST_CONTROLLER:
4030         return port == htons(OFPP_CONTROLLER);
4031     default:
4032         return false;
4033     }
4034 }
4035
4036 /* "Normalizes" the wildcards in 'rule'.  That means:
4037  *
4038  *    1. If the type of level N is known, then only the valid fields for that
4039  *       level may be specified.  For example, ARP does not have a TOS field,
4040  *       so nw_tos must be wildcarded if 'rule' specifies an ARP flow.
4041  *       Similarly, IPv4 does not have any IPv6 addresses, so ipv6_src and
4042  *       ipv6_dst (and other fields) must be wildcarded if 'rule' specifies an
4043  *       IPv4 flow.
4044  *
4045  *    2. If the type of level N is not known (or not understood by Open
4046  *       vSwitch), then no fields at all for that level may be specified.  For
4047  *       example, Open vSwitch does not understand SCTP, an L4 protocol, so the
4048  *       L4 fields tp_src and tp_dst must be wildcarded if 'rule' specifies an
4049  *       SCTP flow.
4050  */
4051 void
4052 ofputil_normalize_rule(struct cls_rule *rule)
4053 {
4054     enum {
4055         MAY_NW_ADDR     = 1 << 0, /* nw_src, nw_dst */
4056         MAY_TP_ADDR     = 1 << 1, /* tp_src, tp_dst */
4057         MAY_NW_PROTO    = 1 << 2, /* nw_proto */
4058         MAY_IPVx        = 1 << 3, /* tos, frag, ttl */
4059         MAY_ARP_SHA     = 1 << 4, /* arp_sha */
4060         MAY_ARP_THA     = 1 << 5, /* arp_tha */
4061         MAY_IPV6        = 1 << 6, /* ipv6_src, ipv6_dst, ipv6_label */
4062         MAY_ND_TARGET   = 1 << 7  /* nd_target */
4063     } may_match;
4064
4065     struct flow_wildcards wc;
4066
4067     /* Figure out what fields may be matched. */
4068     if (rule->flow.dl_type == htons(ETH_TYPE_IP)) {
4069         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_NW_ADDR;
4070         if (rule->flow.nw_proto == IPPROTO_TCP ||
4071             rule->flow.nw_proto == IPPROTO_UDP ||
4072             rule->flow.nw_proto == IPPROTO_ICMP) {
4073             may_match |= MAY_TP_ADDR;
4074         }
4075     } else if (rule->flow.dl_type == htons(ETH_TYPE_IPV6)) {
4076         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_IPV6;
4077         if (rule->flow.nw_proto == IPPROTO_TCP ||
4078             rule->flow.nw_proto == IPPROTO_UDP) {
4079             may_match |= MAY_TP_ADDR;
4080         } else if (rule->flow.nw_proto == IPPROTO_ICMPV6) {
4081             may_match |= MAY_TP_ADDR;
4082             if (rule->flow.tp_src == htons(ND_NEIGHBOR_SOLICIT)) {
4083                 may_match |= MAY_ND_TARGET | MAY_ARP_SHA;
4084             } else if (rule->flow.tp_src == htons(ND_NEIGHBOR_ADVERT)) {
4085                 may_match |= MAY_ND_TARGET | MAY_ARP_THA;
4086             }
4087         }
4088     } else if (rule->flow.dl_type == htons(ETH_TYPE_ARP)) {
4089         may_match = MAY_NW_PROTO | MAY_NW_ADDR | MAY_ARP_SHA | MAY_ARP_THA;
4090     } else {
4091         may_match = 0;
4092     }
4093
4094     /* Clear the fields that may not be matched. */
4095     wc = rule->wc;
4096     if (!(may_match & MAY_NW_ADDR)) {
4097         wc.nw_src_mask = wc.nw_dst_mask = htonl(0);
4098     }
4099     if (!(may_match & MAY_TP_ADDR)) {
4100         wc.tp_src_mask = wc.tp_dst_mask = htons(0);
4101     }
4102     if (!(may_match & MAY_NW_PROTO)) {
4103         wc.wildcards |= FWW_NW_PROTO;
4104     }
4105     if (!(may_match & MAY_IPVx)) {
4106         wc.wildcards |= FWW_NW_DSCP;
4107         wc.wildcards |= FWW_NW_ECN;
4108         wc.wildcards |= FWW_NW_TTL;
4109     }
4110     if (!(may_match & MAY_ARP_SHA)) {
4111         wc.wildcards |= FWW_ARP_SHA;
4112     }
4113     if (!(may_match & MAY_ARP_THA)) {
4114         wc.wildcards |= FWW_ARP_THA;
4115     }
4116     if (!(may_match & MAY_IPV6)) {
4117         wc.ipv6_src_mask = wc.ipv6_dst_mask = in6addr_any;
4118         wc.wildcards |= FWW_IPV6_LABEL;
4119     }
4120     if (!(may_match & MAY_ND_TARGET)) {
4121         wc.nd_target_mask = in6addr_any;
4122     }
4123
4124     /* Log any changes. */
4125     if (!flow_wildcards_equal(&wc, &rule->wc)) {
4126         bool log = !VLOG_DROP_INFO(&bad_ofmsg_rl);
4127         char *pre = log ? cls_rule_to_string(rule) : NULL;
4128
4129         rule->wc = wc;
4130         cls_rule_zero_wildcarded_fields(rule);
4131
4132         if (log) {
4133             char *post = cls_rule_to_string(rule);
4134             VLOG_INFO("normalization changed ofp_match, details:");
4135             VLOG_INFO(" pre: %s", pre);
4136             VLOG_INFO("post: %s", post);
4137             free(pre);
4138             free(post);
4139         }
4140     }
4141 }
4142
4143 /* Attempts to pull 'actions_len' bytes from the front of 'b'.  Returns 0 if
4144  * successful, otherwise an OpenFlow error.
4145  *
4146  * If successful, the first action is stored in '*actionsp' and the number of
4147  * "union ofp_action" size elements into '*n_actionsp'.  Otherwise NULL and 0
4148  * are stored, respectively.
4149  *
4150  * This function does not check that the actions are valid (the caller should
4151  * do so, with validate_actions()).  The caller is also responsible for making
4152  * sure that 'b->data' is initially aligned appropriately for "union
4153  * ofp_action". */
4154 enum ofperr
4155 ofputil_pull_actions(struct ofpbuf *b, unsigned int actions_len,
4156                      union ofp_action **actionsp, size_t *n_actionsp)
4157 {
4158     if (actions_len % OFP_ACTION_ALIGN != 0) {
4159         VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
4160                      "is not a multiple of %d", actions_len, OFP_ACTION_ALIGN);
4161         goto error;
4162     }
4163
4164     *actionsp = ofpbuf_try_pull(b, actions_len);
4165     if (*actionsp == NULL) {
4166         VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
4167                      "exceeds remaining message length (%zu)",
4168                      actions_len, b->size);
4169         goto error;
4170     }
4171
4172     *n_actionsp = actions_len / OFP_ACTION_ALIGN;
4173     return 0;
4174
4175 error:
4176     *actionsp = NULL;
4177     *n_actionsp = 0;
4178     return OFPERR_OFPBRC_BAD_LEN;
4179 }
4180
4181 bool
4182 ofputil_actions_equal(const union ofp_action *a, size_t n_a,
4183                       const union ofp_action *b, size_t n_b)
4184 {
4185     return n_a == n_b && (!n_a || !memcmp(a, b, n_a * sizeof *a));
4186 }
4187
4188 union ofp_action *
4189 ofputil_actions_clone(const union ofp_action *actions, size_t n)
4190 {
4191     return n ? xmemdup(actions, n * sizeof *actions) : NULL;
4192 }
4193
4194 /* Parses a key or a key-value pair from '*stringp'.
4195  *
4196  * On success: Stores the key into '*keyp'.  Stores the value, if present, into
4197  * '*valuep', otherwise an empty string.  Advances '*stringp' past the end of
4198  * the key-value pair, preparing it for another call.  '*keyp' and '*valuep'
4199  * are substrings of '*stringp' created by replacing some of its bytes by null
4200  * terminators.  Returns true.
4201  *
4202  * If '*stringp' is just white space or commas, sets '*keyp' and '*valuep' to
4203  * NULL and returns false. */
4204 bool
4205 ofputil_parse_key_value(char **stringp, char **keyp, char **valuep)
4206 {
4207     char *pos, *key, *value;
4208     size_t key_len;
4209
4210     pos = *stringp;
4211     pos += strspn(pos, ", \t\r\n");
4212     if (*pos == '\0') {
4213         *keyp = *valuep = NULL;
4214         return false;
4215     }
4216
4217     key = pos;
4218     key_len = strcspn(pos, ":=(, \t\r\n");
4219     if (key[key_len] == ':' || key[key_len] == '=') {
4220         /* The value can be separated by a colon. */
4221         size_t value_len;
4222
4223         value = key + key_len + 1;
4224         value_len = strcspn(value, ", \t\r\n");
4225         pos = value + value_len + (value[value_len] != '\0');
4226         value[value_len] = '\0';
4227     } else if (key[key_len] == '(') {
4228         /* The value can be surrounded by balanced parentheses.  The outermost
4229          * set of parentheses is removed. */
4230         int level = 1;
4231         size_t value_len;
4232
4233         value = key + key_len + 1;
4234         for (value_len = 0; level > 0; value_len++) {
4235             switch (value[value_len]) {
4236             case '\0':
4237                 level = 0;
4238                 break;
4239
4240             case '(':
4241                 level++;
4242                 break;
4243
4244             case ')':
4245                 level--;
4246                 break;
4247             }
4248         }
4249         value[value_len - 1] = '\0';
4250         pos = value + value_len;
4251     } else {
4252         /* There might be no value at all. */
4253         value = key + key_len;  /* Will become the empty string below. */
4254         pos = key + key_len + (key[key_len] != '\0');
4255     }
4256     key[key_len] = '\0';
4257
4258     *stringp = pos;
4259     *keyp = key;
4260     *valuep = value;
4261     return true;
4262 }