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