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