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