ofp-util: Don't return static data in ofputil_packet_in_reason_to_string().
[sliver-openvswitch.git] / lib / ofp-util.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 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 <ctype.h>
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <sys/types.h>
23 #include <netinet/in.h>
24 #include <netinet/icmp6.h>
25 #include <stdlib.h>
26 #include "bundle.h"
27 #include "byte-order.h"
28 #include "classifier.h"
29 #include "dynamic-string.h"
30 #include "learn.h"
31 #include "meta-flow.h"
32 #include "multipath.h"
33 #include "netdev.h"
34 #include "nx-match.h"
35 #include "ofp-actions.h"
36 #include "ofp-errors.h"
37 #include "ofp-msgs.h"
38 #include "ofp-util.h"
39 #include "ofpbuf.h"
40 #include "packets.h"
41 #include "random.h"
42 #include "unaligned.h"
43 #include "type-props.h"
44 #include "vlog.h"
45
46 VLOG_DEFINE_THIS_MODULE(ofp_util);
47
48 /* Rate limit for OpenFlow message parse errors.  These always indicate a bug
49  * in the peer and so there's not much point in showing a lot of them. */
50 static struct vlog_rate_limit bad_ofmsg_rl = VLOG_RATE_LIMIT_INIT(1, 5);
51
52 /* Given the wildcard bit count in the least-significant 6 of 'wcbits', returns
53  * an IP netmask with a 1 in each bit that must match and a 0 in each bit that
54  * is wildcarded.
55  *
56  * The bits in 'wcbits' are in the format used in enum ofp_flow_wildcards: 0
57  * is exact match, 1 ignores the LSB, 2 ignores the 2 least-significant bits,
58  * ..., 32 and higher wildcard the entire field.  This is the *opposite* of the
59  * usual convention where e.g. /24 indicates that 8 bits (not 24 bits) are
60  * wildcarded. */
61 ovs_be32
62 ofputil_wcbits_to_netmask(int wcbits)
63 {
64     wcbits &= 0x3f;
65     return wcbits < 32 ? htonl(~((1u << wcbits) - 1)) : 0;
66 }
67
68 /* Given the IP netmask 'netmask', returns the number of bits of the IP address
69  * that it wildcards, that is, the number of 0-bits in 'netmask', a number
70  * between 0 and 32 inclusive.
71  *
72  * If 'netmask' is not a CIDR netmask (see ip_is_cidr()), the return value will
73  * still be in the valid range but isn't otherwise meaningful. */
74 int
75 ofputil_netmask_to_wcbits(ovs_be32 netmask)
76 {
77     return 32 - ip_count_cidr_bits(netmask);
78 }
79
80 /* Converts the OpenFlow 1.0 wildcards in 'ofpfw' (OFPFW10_*) into a
81  * flow_wildcards in 'wc' for use in struct match.  It is the caller's
82  * responsibility to handle the special case where the flow match's dl_vlan is
83  * set to OFP_VLAN_NONE. */
84 void
85 ofputil_wildcard_from_ofpfw10(uint32_t ofpfw, struct flow_wildcards *wc)
86 {
87     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 20);
88
89     /* Initialize most of wc. */
90     flow_wildcards_init_catchall(wc);
91
92     if (!(ofpfw & OFPFW10_IN_PORT)) {
93         wc->masks.in_port = UINT16_MAX;
94     }
95
96     if (!(ofpfw & OFPFW10_NW_TOS)) {
97         wc->masks.nw_tos |= IP_DSCP_MASK;
98     }
99
100     if (!(ofpfw & OFPFW10_NW_PROTO)) {
101         wc->masks.nw_proto = UINT8_MAX;
102     }
103     wc->masks.nw_src = ofputil_wcbits_to_netmask(ofpfw
104                                                  >> OFPFW10_NW_SRC_SHIFT);
105     wc->masks.nw_dst = ofputil_wcbits_to_netmask(ofpfw
106                                                  >> OFPFW10_NW_DST_SHIFT);
107
108     if (!(ofpfw & OFPFW10_TP_SRC)) {
109         wc->masks.tp_src = htons(UINT16_MAX);
110     }
111     if (!(ofpfw & OFPFW10_TP_DST)) {
112         wc->masks.tp_dst = htons(UINT16_MAX);
113     }
114
115     if (!(ofpfw & OFPFW10_DL_SRC)) {
116         memset(wc->masks.dl_src, 0xff, ETH_ADDR_LEN);
117     }
118     if (!(ofpfw & OFPFW10_DL_DST)) {
119         memset(wc->masks.dl_dst, 0xff, ETH_ADDR_LEN);
120     }
121     if (!(ofpfw & OFPFW10_DL_TYPE)) {
122         wc->masks.dl_type = htons(UINT16_MAX);
123     }
124
125     /* VLAN TCI mask. */
126     if (!(ofpfw & OFPFW10_DL_VLAN_PCP)) {
127         wc->masks.vlan_tci |= htons(VLAN_PCP_MASK | VLAN_CFI);
128     }
129     if (!(ofpfw & OFPFW10_DL_VLAN)) {
130         wc->masks.vlan_tci |= htons(VLAN_VID_MASK | VLAN_CFI);
131     }
132 }
133
134 /* Converts the ofp10_match in 'ofmatch' into a struct match in 'match'. */
135 void
136 ofputil_match_from_ofp10_match(const struct ofp10_match *ofmatch,
137                                struct match *match)
138 {
139     uint32_t ofpfw = ntohl(ofmatch->wildcards) & OFPFW10_ALL;
140
141     /* Initialize match->wc. */
142     memset(&match->flow, 0, sizeof match->flow);
143     ofputil_wildcard_from_ofpfw10(ofpfw, &match->wc);
144
145     /* Initialize most of match->flow. */
146     match->flow.nw_src = ofmatch->nw_src;
147     match->flow.nw_dst = ofmatch->nw_dst;
148     match->flow.in_port = ntohs(ofmatch->in_port);
149     match->flow.dl_type = ofputil_dl_type_from_openflow(ofmatch->dl_type);
150     match->flow.tp_src = ofmatch->tp_src;
151     match->flow.tp_dst = ofmatch->tp_dst;
152     memcpy(match->flow.dl_src, ofmatch->dl_src, ETH_ADDR_LEN);
153     memcpy(match->flow.dl_dst, ofmatch->dl_dst, ETH_ADDR_LEN);
154     match->flow.nw_tos = ofmatch->nw_tos & IP_DSCP_MASK;
155     match->flow.nw_proto = ofmatch->nw_proto;
156
157     /* Translate VLANs. */
158     if (!(ofpfw & OFPFW10_DL_VLAN) &&
159         ofmatch->dl_vlan == htons(OFP10_VLAN_NONE)) {
160         /* Match only packets without 802.1Q header.
161          *
162          * When OFPFW10_DL_VLAN_PCP is wildcarded, this is obviously correct.
163          *
164          * If OFPFW10_DL_VLAN_PCP is matched, the flow match is contradictory,
165          * because we can't have a specific PCP without an 802.1Q header.
166          * However, older versions of OVS treated this as matching packets
167          * withut an 802.1Q header, so we do here too. */
168         match->flow.vlan_tci = htons(0);
169         match->wc.masks.vlan_tci = htons(0xffff);
170     } else {
171         ovs_be16 vid, pcp, tci;
172
173         vid = ofmatch->dl_vlan & htons(VLAN_VID_MASK);
174         pcp = htons((ofmatch->dl_vlan_pcp << VLAN_PCP_SHIFT) & VLAN_PCP_MASK);
175         tci = vid | pcp | htons(VLAN_CFI);
176         match->flow.vlan_tci = tci & match->wc.masks.vlan_tci;
177     }
178
179     /* Clean up. */
180     match_zero_wildcarded_fields(match);
181 }
182
183 /* Convert 'match' into the OpenFlow 1.0 match structure 'ofmatch'. */
184 void
185 ofputil_match_to_ofp10_match(const struct match *match,
186                              struct ofp10_match *ofmatch)
187 {
188     const struct flow_wildcards *wc = &match->wc;
189     uint32_t ofpfw;
190
191     /* Figure out most OpenFlow wildcards. */
192     ofpfw = 0;
193     if (!wc->masks.in_port) {
194         ofpfw |= OFPFW10_IN_PORT;
195     }
196     if (!wc->masks.dl_type) {
197         ofpfw |= OFPFW10_DL_TYPE;
198     }
199     if (!wc->masks.nw_proto) {
200         ofpfw |= OFPFW10_NW_PROTO;
201     }
202     ofpfw |= (ofputil_netmask_to_wcbits(wc->masks.nw_src)
203               << OFPFW10_NW_SRC_SHIFT);
204     ofpfw |= (ofputil_netmask_to_wcbits(wc->masks.nw_dst)
205               << OFPFW10_NW_DST_SHIFT);
206     if (!(wc->masks.nw_tos & IP_DSCP_MASK)) {
207         ofpfw |= OFPFW10_NW_TOS;
208     }
209     if (!wc->masks.tp_src) {
210         ofpfw |= OFPFW10_TP_SRC;
211     }
212     if (!wc->masks.tp_dst) {
213         ofpfw |= OFPFW10_TP_DST;
214     }
215     if (eth_addr_is_zero(wc->masks.dl_src)) {
216         ofpfw |= OFPFW10_DL_SRC;
217     }
218     if (eth_addr_is_zero(wc->masks.dl_dst)) {
219         ofpfw |= OFPFW10_DL_DST;
220     }
221
222     /* Translate VLANs. */
223     ofmatch->dl_vlan = htons(0);
224     ofmatch->dl_vlan_pcp = 0;
225     if (match->wc.masks.vlan_tci == htons(0)) {
226         ofpfw |= OFPFW10_DL_VLAN | OFPFW10_DL_VLAN_PCP;
227     } else if (match->wc.masks.vlan_tci & htons(VLAN_CFI)
228                && !(match->flow.vlan_tci & htons(VLAN_CFI))) {
229         ofmatch->dl_vlan = htons(OFP10_VLAN_NONE);
230         ofpfw |= OFPFW10_DL_VLAN_PCP;
231     } else {
232         if (!(match->wc.masks.vlan_tci & htons(VLAN_VID_MASK))) {
233             ofpfw |= OFPFW10_DL_VLAN;
234         } else {
235             ofmatch->dl_vlan = htons(vlan_tci_to_vid(match->flow.vlan_tci));
236         }
237
238         if (!(match->wc.masks.vlan_tci & htons(VLAN_PCP_MASK))) {
239             ofpfw |= OFPFW10_DL_VLAN_PCP;
240         } else {
241             ofmatch->dl_vlan_pcp = vlan_tci_to_pcp(match->flow.vlan_tci);
242         }
243     }
244
245     /* Compose most of the match structure. */
246     ofmatch->wildcards = htonl(ofpfw);
247     ofmatch->in_port = htons(match->flow.in_port);
248     memcpy(ofmatch->dl_src, match->flow.dl_src, ETH_ADDR_LEN);
249     memcpy(ofmatch->dl_dst, match->flow.dl_dst, ETH_ADDR_LEN);
250     ofmatch->dl_type = ofputil_dl_type_to_openflow(match->flow.dl_type);
251     ofmatch->nw_src = match->flow.nw_src;
252     ofmatch->nw_dst = match->flow.nw_dst;
253     ofmatch->nw_tos = match->flow.nw_tos & IP_DSCP_MASK;
254     ofmatch->nw_proto = match->flow.nw_proto;
255     ofmatch->tp_src = match->flow.tp_src;
256     ofmatch->tp_dst = match->flow.tp_dst;
257     memset(ofmatch->pad1, '\0', sizeof ofmatch->pad1);
258     memset(ofmatch->pad2, '\0', sizeof ofmatch->pad2);
259 }
260
261 enum ofperr
262 ofputil_pull_ofp11_match(struct ofpbuf *buf, struct match *match,
263                          uint16_t *padded_match_len)
264 {
265     struct ofp11_match_header *omh = buf->data;
266     uint16_t match_len;
267
268     if (buf->size < sizeof *omh) {
269         return OFPERR_OFPBMC_BAD_LEN;
270     }
271
272     match_len = ntohs(omh->length);
273
274     switch (ntohs(omh->type)) {
275     case OFPMT_STANDARD: {
276         struct ofp11_match *om;
277
278         if (match_len != sizeof *om || buf->size < sizeof *om) {
279             return OFPERR_OFPBMC_BAD_LEN;
280         }
281         om = ofpbuf_pull(buf, sizeof *om);
282         if (padded_match_len) {
283             *padded_match_len = match_len;
284         }
285         return ofputil_match_from_ofp11_match(om, match);
286     }
287
288     case OFPMT_OXM:
289         if (padded_match_len) {
290             *padded_match_len = ROUND_UP(match_len, 8);
291         }
292         return oxm_pull_match(buf, match);
293
294     default:
295         return OFPERR_OFPBMC_BAD_TYPE;
296     }
297 }
298
299 /* Converts the ofp11_match in 'match' into a struct match in 'match.  Returns
300  * 0 if successful, otherwise an OFPERR_* value. */
301 enum ofperr
302 ofputil_match_from_ofp11_match(const struct ofp11_match *ofmatch,
303                                struct match *match)
304 {
305     uint16_t wc = ntohl(ofmatch->wildcards);
306     uint8_t dl_src_mask[ETH_ADDR_LEN];
307     uint8_t dl_dst_mask[ETH_ADDR_LEN];
308     bool ipv4, arp, rarp;
309     int i;
310
311     match_init_catchall(match);
312
313     if (!(wc & OFPFW11_IN_PORT)) {
314         uint16_t ofp_port;
315         enum ofperr error;
316
317         error = ofputil_port_from_ofp11(ofmatch->in_port, &ofp_port);
318         if (error) {
319             return OFPERR_OFPBMC_BAD_VALUE;
320         }
321         match_set_in_port(match, ofp_port);
322     }
323
324     for (i = 0; i < ETH_ADDR_LEN; i++) {
325         dl_src_mask[i] = ~ofmatch->dl_src_mask[i];
326     }
327     match_set_dl_src_masked(match, ofmatch->dl_src, dl_src_mask);
328
329     for (i = 0; i < ETH_ADDR_LEN; i++) {
330         dl_dst_mask[i] = ~ofmatch->dl_dst_mask[i];
331     }
332     match_set_dl_dst_masked(match, ofmatch->dl_dst, dl_dst_mask);
333
334     if (!(wc & OFPFW11_DL_VLAN)) {
335         if (ofmatch->dl_vlan == htons(OFPVID11_NONE)) {
336             /* Match only packets without a VLAN tag. */
337             match->flow.vlan_tci = htons(0);
338             match->wc.masks.vlan_tci = htons(UINT16_MAX);
339         } else {
340             if (ofmatch->dl_vlan == htons(OFPVID11_ANY)) {
341                 /* Match any packet with a VLAN tag regardless of VID. */
342                 match->flow.vlan_tci = htons(VLAN_CFI);
343                 match->wc.masks.vlan_tci = htons(VLAN_CFI);
344             } else if (ntohs(ofmatch->dl_vlan) < 4096) {
345                 /* Match only packets with the specified VLAN VID. */
346                 match->flow.vlan_tci = htons(VLAN_CFI) | ofmatch->dl_vlan;
347                 match->wc.masks.vlan_tci = htons(VLAN_CFI | VLAN_VID_MASK);
348             } else {
349                 /* Invalid VID. */
350                 return OFPERR_OFPBMC_BAD_VALUE;
351             }
352
353             if (!(wc & OFPFW11_DL_VLAN_PCP)) {
354                 if (ofmatch->dl_vlan_pcp <= 7) {
355                     match->flow.vlan_tci |= htons(ofmatch->dl_vlan_pcp
356                                                   << VLAN_PCP_SHIFT);
357                     match->wc.masks.vlan_tci |= htons(VLAN_PCP_MASK);
358                 } else {
359                     /* Invalid PCP. */
360                     return OFPERR_OFPBMC_BAD_VALUE;
361                 }
362             }
363         }
364     }
365
366     if (!(wc & OFPFW11_DL_TYPE)) {
367         match_set_dl_type(match,
368                           ofputil_dl_type_from_openflow(ofmatch->dl_type));
369     }
370
371     ipv4 = match->flow.dl_type == htons(ETH_TYPE_IP);
372     arp = match->flow.dl_type == htons(ETH_TYPE_ARP);
373     rarp = match->flow.dl_type == htons(ETH_TYPE_RARP);
374
375     if (ipv4 && !(wc & OFPFW11_NW_TOS)) {
376         if (ofmatch->nw_tos & ~IP_DSCP_MASK) {
377             /* Invalid TOS. */
378             return OFPERR_OFPBMC_BAD_VALUE;
379         }
380
381         match_set_nw_dscp(match, ofmatch->nw_tos);
382     }
383
384     if (ipv4 || arp || rarp) {
385         if (!(wc & OFPFW11_NW_PROTO)) {
386             match_set_nw_proto(match, ofmatch->nw_proto);
387         }
388         match_set_nw_src_masked(match, ofmatch->nw_src, ~ofmatch->nw_src_mask);
389         match_set_nw_dst_masked(match, ofmatch->nw_dst, ~ofmatch->nw_dst_mask);
390     }
391
392 #define OFPFW11_TP_ALL (OFPFW11_TP_SRC | OFPFW11_TP_DST)
393     if (ipv4 && (wc & OFPFW11_TP_ALL) != OFPFW11_TP_ALL) {
394         switch (match->flow.nw_proto) {
395         case IPPROTO_ICMP:
396             /* "A.2.3 Flow Match Structures" in OF1.1 says:
397              *
398              *    The tp_src and tp_dst fields will be ignored unless the
399              *    network protocol specified is as TCP, UDP or SCTP.
400              *
401              * but I'm pretty sure we should support ICMP too, otherwise
402              * that's a regression from OF1.0. */
403             if (!(wc & OFPFW11_TP_SRC)) {
404                 uint16_t icmp_type = ntohs(ofmatch->tp_src);
405                 if (icmp_type < 0x100) {
406                     match_set_icmp_type(match, icmp_type);
407                 } else {
408                     return OFPERR_OFPBMC_BAD_FIELD;
409                 }
410             }
411             if (!(wc & OFPFW11_TP_DST)) {
412                 uint16_t icmp_code = ntohs(ofmatch->tp_dst);
413                 if (icmp_code < 0x100) {
414                     match_set_icmp_code(match, icmp_code);
415                 } else {
416                     return OFPERR_OFPBMC_BAD_FIELD;
417                 }
418             }
419             break;
420
421         case IPPROTO_TCP:
422         case IPPROTO_UDP:
423             if (!(wc & (OFPFW11_TP_SRC))) {
424                 match_set_tp_src(match, ofmatch->tp_src);
425             }
426             if (!(wc & (OFPFW11_TP_DST))) {
427                 match_set_tp_dst(match, ofmatch->tp_dst);
428             }
429             break;
430
431         case IPPROTO_SCTP:
432             /* We don't support SCTP and it seems that we should tell the
433              * controller, since OF1.1 implementations are supposed to. */
434             return OFPERR_OFPBMC_BAD_FIELD;
435
436         default:
437             /* OF1.1 says explicitly to ignore this. */
438             break;
439         }
440     }
441
442     if (eth_type_mpls(match->flow.dl_type)) {
443         enum { OFPFW11_MPLS_ALL = OFPFW11_MPLS_LABEL | OFPFW11_MPLS_TC };
444
445         if ((wc & OFPFW11_MPLS_ALL) != OFPFW11_MPLS_ALL) {
446             /* MPLS not supported. */
447             return OFPERR_OFPBMC_BAD_TAG;
448         }
449     }
450
451     match_set_metadata_masked(match, ofmatch->metadata,
452                               ~ofmatch->metadata_mask);
453
454     return 0;
455 }
456
457 /* Convert 'match' into the OpenFlow 1.1 match structure 'ofmatch'. */
458 void
459 ofputil_match_to_ofp11_match(const struct match *match,
460                              struct ofp11_match *ofmatch)
461 {
462     uint32_t wc = 0;
463     int i;
464
465     memset(ofmatch, 0, sizeof *ofmatch);
466     ofmatch->omh.type = htons(OFPMT_STANDARD);
467     ofmatch->omh.length = htons(OFPMT11_STANDARD_LENGTH);
468
469     if (!match->wc.masks.in_port) {
470         wc |= OFPFW11_IN_PORT;
471     } else {
472         ofmatch->in_port = ofputil_port_to_ofp11(match->flow.in_port);
473     }
474
475     memcpy(ofmatch->dl_src, match->flow.dl_src, ETH_ADDR_LEN);
476     for (i = 0; i < ETH_ADDR_LEN; i++) {
477         ofmatch->dl_src_mask[i] = ~match->wc.masks.dl_src[i];
478     }
479
480     memcpy(ofmatch->dl_dst, match->flow.dl_dst, ETH_ADDR_LEN);
481     for (i = 0; i < ETH_ADDR_LEN; i++) {
482         ofmatch->dl_dst_mask[i] = ~match->wc.masks.dl_dst[i];
483     }
484
485     if (match->wc.masks.vlan_tci == htons(0)) {
486         wc |= OFPFW11_DL_VLAN | OFPFW11_DL_VLAN_PCP;
487     } else if (match->wc.masks.vlan_tci & htons(VLAN_CFI)
488                && !(match->flow.vlan_tci & htons(VLAN_CFI))) {
489         ofmatch->dl_vlan = htons(OFPVID11_NONE);
490         wc |= OFPFW11_DL_VLAN_PCP;
491     } else {
492         if (!(match->wc.masks.vlan_tci & htons(VLAN_VID_MASK))) {
493             ofmatch->dl_vlan = htons(OFPVID11_ANY);
494         } else {
495             ofmatch->dl_vlan = htons(vlan_tci_to_vid(match->flow.vlan_tci));
496         }
497
498         if (!(match->wc.masks.vlan_tci & htons(VLAN_PCP_MASK))) {
499             wc |= OFPFW11_DL_VLAN_PCP;
500         } else {
501             ofmatch->dl_vlan_pcp = vlan_tci_to_pcp(match->flow.vlan_tci);
502         }
503     }
504
505     if (!match->wc.masks.dl_type) {
506         wc |= OFPFW11_DL_TYPE;
507     } else {
508         ofmatch->dl_type = ofputil_dl_type_to_openflow(match->flow.dl_type);
509     }
510
511     if (!(match->wc.masks.nw_tos & IP_DSCP_MASK)) {
512         wc |= OFPFW11_NW_TOS;
513     } else {
514         ofmatch->nw_tos = match->flow.nw_tos & IP_DSCP_MASK;
515     }
516
517     if (!match->wc.masks.nw_proto) {
518         wc |= OFPFW11_NW_PROTO;
519     } else {
520         ofmatch->nw_proto = match->flow.nw_proto;
521     }
522
523     ofmatch->nw_src = match->flow.nw_src;
524     ofmatch->nw_src_mask = ~match->wc.masks.nw_src;
525     ofmatch->nw_dst = match->flow.nw_dst;
526     ofmatch->nw_dst_mask = ~match->wc.masks.nw_dst;
527
528     if (!match->wc.masks.tp_src) {
529         wc |= OFPFW11_TP_SRC;
530     } else {
531         ofmatch->tp_src = match->flow.tp_src;
532     }
533
534     if (!match->wc.masks.tp_dst) {
535         wc |= OFPFW11_TP_DST;
536     } else {
537         ofmatch->tp_dst = match->flow.tp_dst;
538     }
539
540     /* MPLS not supported. */
541     wc |= OFPFW11_MPLS_LABEL;
542     wc |= OFPFW11_MPLS_TC;
543
544     ofmatch->metadata = match->flow.metadata;
545     ofmatch->metadata_mask = ~match->wc.masks.metadata;
546
547     ofmatch->wildcards = htonl(wc);
548 }
549
550 /* Given a 'dl_type' value in the format used in struct flow, returns the
551  * corresponding 'dl_type' value for use in an ofp10_match or ofp11_match
552  * structure. */
553 ovs_be16
554 ofputil_dl_type_to_openflow(ovs_be16 flow_dl_type)
555 {
556     return (flow_dl_type == htons(FLOW_DL_TYPE_NONE)
557             ? htons(OFP_DL_TYPE_NOT_ETH_TYPE)
558             : flow_dl_type);
559 }
560
561 /* Given a 'dl_type' value in the format used in an ofp10_match or ofp11_match
562  * structure, returns the corresponding 'dl_type' value for use in struct
563  * flow. */
564 ovs_be16
565 ofputil_dl_type_from_openflow(ovs_be16 ofp_dl_type)
566 {
567     return (ofp_dl_type == htons(OFP_DL_TYPE_NOT_ETH_TYPE)
568             ? htons(FLOW_DL_TYPE_NONE)
569             : ofp_dl_type);
570 }
571 \f
572 /* Protocols. */
573
574 struct proto_abbrev {
575     enum ofputil_protocol protocol;
576     const char *name;
577 };
578
579 /* Most users really don't care about some of the differences between
580  * protocols.  These abbreviations help with that. */
581 static const struct proto_abbrev proto_abbrevs[] = {
582     { OFPUTIL_P_ANY,          "any" },
583     { OFPUTIL_P_OF10_STD_ANY, "OpenFlow10" },
584     { OFPUTIL_P_OF10_NXM_ANY, "NXM" },
585     { OFPUTIL_P_ANY_OXM,      "OXM" },
586 };
587 #define N_PROTO_ABBREVS ARRAY_SIZE(proto_abbrevs)
588
589 enum ofputil_protocol ofputil_flow_dump_protocols[] = {
590     OFPUTIL_P_OF13_OXM,
591     OFPUTIL_P_OF12_OXM,
592     OFPUTIL_P_OF10_NXM,
593     OFPUTIL_P_OF10_STD,
594 };
595 size_t ofputil_n_flow_dump_protocols = ARRAY_SIZE(ofputil_flow_dump_protocols);
596
597 /* Returns the set of ofputil_protocols that are supported with the given
598  * OpenFlow 'version'.  'version' should normally be an 8-bit OpenFlow version
599  * identifier (e.g. 0x01 for OpenFlow 1.0, 0x02 for OpenFlow 1.1).  Returns 0
600  * if 'version' is not supported or outside the valid range.  */
601 enum ofputil_protocol
602 ofputil_protocols_from_ofp_version(enum ofp_version version)
603 {
604     switch (version) {
605     case OFP10_VERSION:
606         return OFPUTIL_P_OF10_STD_ANY | OFPUTIL_P_OF10_NXM_ANY;
607     case OFP12_VERSION:
608         return OFPUTIL_P_OF12_OXM;
609     case OFP13_VERSION:
610         return OFPUTIL_P_OF13_OXM;
611     case OFP11_VERSION:
612     default:
613         return 0;
614     }
615 }
616
617 /* Returns the ofputil_protocol that is initially in effect on an OpenFlow
618  * connection that has negotiated the given 'version'.  'version' should
619  * normally be an 8-bit OpenFlow version identifier (e.g. 0x01 for OpenFlow
620  * 1.0, 0x02 for OpenFlow 1.1).  Returns 0 if 'version' is not supported or
621  * outside the valid range.  */
622 enum ofputil_protocol
623 ofputil_protocol_from_ofp_version(enum ofp_version version)
624 {
625     return rightmost_1bit(ofputil_protocols_from_ofp_version(version));
626 }
627
628 /* Returns the OpenFlow protocol version number (e.g. OFP10_VERSION,
629  * etc.) that corresponds to 'protocol'. */
630 enum ofp_version
631 ofputil_protocol_to_ofp_version(enum ofputil_protocol protocol)
632 {
633     switch (protocol) {
634     case OFPUTIL_P_OF10_STD:
635     case OFPUTIL_P_OF10_STD_TID:
636     case OFPUTIL_P_OF10_NXM:
637     case OFPUTIL_P_OF10_NXM_TID:
638         return OFP10_VERSION;
639     case OFPUTIL_P_OF12_OXM:
640         return OFP12_VERSION;
641     case OFPUTIL_P_OF13_OXM:
642         return OFP13_VERSION;
643     }
644
645     NOT_REACHED();
646 }
647
648 /* Returns a bitmap of OpenFlow versions that are supported by at
649  * least one of the 'protocols'. */
650 uint32_t
651 ofputil_protocols_to_version_bitmap(enum ofputil_protocol protocols)
652 {
653     uint32_t bitmap = 0;
654
655     for (; protocols; protocols = zero_rightmost_1bit(protocols)) {
656         enum ofputil_protocol protocol = rightmost_1bit(protocols);
657
658         bitmap |= 1u << ofputil_protocol_to_ofp_version(protocol);
659     }
660
661     return bitmap;
662 }
663
664 /* Returns the set of protocols that are supported on top of the
665  * OpenFlow versions included in 'bitmap'. */
666 enum ofputil_protocol
667 ofputil_protocols_from_version_bitmap(uint32_t bitmap)
668 {
669     enum ofputil_protocol protocols = 0;
670
671     for (; bitmap; bitmap = zero_rightmost_1bit(bitmap)) {
672         enum ofp_version version = rightmost_1bit_idx(bitmap);
673
674         protocols |= ofputil_protocols_from_ofp_version(version);
675     }
676
677     return protocols;
678 }
679
680 /* Returns true if 'protocol' is a single OFPUTIL_P_* value, false
681  * otherwise. */
682 bool
683 ofputil_protocol_is_valid(enum ofputil_protocol protocol)
684 {
685     return protocol & OFPUTIL_P_ANY && is_pow2(protocol);
686 }
687
688 /* Returns the equivalent of 'protocol' with the Nicira flow_mod_table_id
689  * extension turned on or off if 'enable' is true or false, respectively.
690  *
691  * This extension is only useful for protocols whose "standard" version does
692  * not allow specific tables to be modified.  In particular, this is true of
693  * OpenFlow 1.0.  In later versions of OpenFlow, a flow_mod request always
694  * specifies a table ID and so there is no need for such an extension.  When
695  * 'protocol' is such a protocol that doesn't need a flow_mod_table_id
696  * extension, this function just returns its 'protocol' argument unchanged
697  * regardless of the value of 'enable'.  */
698 enum ofputil_protocol
699 ofputil_protocol_set_tid(enum ofputil_protocol protocol, bool enable)
700 {
701     switch (protocol) {
702     case OFPUTIL_P_OF10_STD:
703     case OFPUTIL_P_OF10_STD_TID:
704         return enable ? OFPUTIL_P_OF10_STD_TID : OFPUTIL_P_OF10_STD;
705
706     case OFPUTIL_P_OF10_NXM:
707     case OFPUTIL_P_OF10_NXM_TID:
708         return enable ? OFPUTIL_P_OF10_NXM_TID : OFPUTIL_P_OF10_NXM;
709
710     case OFPUTIL_P_OF12_OXM:
711         return OFPUTIL_P_OF12_OXM;
712
713     case OFPUTIL_P_OF13_OXM:
714         return OFPUTIL_P_OF13_OXM;
715
716     default:
717         NOT_REACHED();
718     }
719 }
720
721 /* Returns the "base" version of 'protocol'.  That is, if 'protocol' includes
722  * some extension to a standard protocol version, the return value is the
723  * standard version of that protocol without any extension.  If 'protocol' is a
724  * standard protocol version, returns 'protocol' unchanged. */
725 enum ofputil_protocol
726 ofputil_protocol_to_base(enum ofputil_protocol protocol)
727 {
728     return ofputil_protocol_set_tid(protocol, false);
729 }
730
731 /* Returns 'new_base' with any extensions taken from 'cur'. */
732 enum ofputil_protocol
733 ofputil_protocol_set_base(enum ofputil_protocol cur,
734                           enum ofputil_protocol new_base)
735 {
736     bool tid = (cur & OFPUTIL_P_TID) != 0;
737
738     switch (new_base) {
739     case OFPUTIL_P_OF10_STD:
740     case OFPUTIL_P_OF10_STD_TID:
741         return ofputil_protocol_set_tid(OFPUTIL_P_OF10_STD, tid);
742
743     case OFPUTIL_P_OF10_NXM:
744     case OFPUTIL_P_OF10_NXM_TID:
745         return ofputil_protocol_set_tid(OFPUTIL_P_OF10_NXM, tid);
746
747     case OFPUTIL_P_OF12_OXM:
748         return ofputil_protocol_set_tid(OFPUTIL_P_OF12_OXM, tid);
749
750     case OFPUTIL_P_OF13_OXM:
751         return ofputil_protocol_set_tid(OFPUTIL_P_OF13_OXM, tid);
752
753     default:
754         NOT_REACHED();
755     }
756 }
757
758 /* Returns a string form of 'protocol', if a simple form exists (that is, if
759  * 'protocol' is either a single protocol or it is a combination of protocols
760  * that have a single abbreviation).  Otherwise, returns NULL. */
761 const char *
762 ofputil_protocol_to_string(enum ofputil_protocol protocol)
763 {
764     const struct proto_abbrev *p;
765
766     /* Use a "switch" statement for single-bit names so that we get a compiler
767      * warning if we forget any. */
768     switch (protocol) {
769     case OFPUTIL_P_OF10_NXM:
770         return "NXM-table_id";
771
772     case OFPUTIL_P_OF10_NXM_TID:
773         return "NXM+table_id";
774
775     case OFPUTIL_P_OF10_STD:
776         return "OpenFlow10-table_id";
777
778     case OFPUTIL_P_OF10_STD_TID:
779         return "OpenFlow10+table_id";
780
781     case OFPUTIL_P_OF12_OXM:
782         return "OXM-OpenFlow12";
783
784     case OFPUTIL_P_OF13_OXM:
785         return "OXM-OpenFlow13";
786     }
787
788     /* Check abbreviations. */
789     for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
790         if (protocol == p->protocol) {
791             return p->name;
792         }
793     }
794
795     return NULL;
796 }
797
798 /* Returns a string that represents 'protocols'.  The return value might be a
799  * comma-separated list if 'protocols' doesn't have a simple name.  The return
800  * value is "none" if 'protocols' is 0.
801  *
802  * The caller must free the returned string (with free()). */
803 char *
804 ofputil_protocols_to_string(enum ofputil_protocol protocols)
805 {
806     struct ds s;
807
808     ovs_assert(!(protocols & ~OFPUTIL_P_ANY));
809     if (protocols == 0) {
810         return xstrdup("none");
811     }
812
813     ds_init(&s);
814     while (protocols) {
815         const struct proto_abbrev *p;
816         int i;
817
818         if (s.length) {
819             ds_put_char(&s, ',');
820         }
821
822         for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
823             if ((protocols & p->protocol) == p->protocol) {
824                 ds_put_cstr(&s, p->name);
825                 protocols &= ~p->protocol;
826                 goto match;
827             }
828         }
829
830         for (i = 0; i < CHAR_BIT * sizeof(enum ofputil_protocol); i++) {
831             enum ofputil_protocol bit = 1u << i;
832
833             if (protocols & bit) {
834                 ds_put_cstr(&s, ofputil_protocol_to_string(bit));
835                 protocols &= ~bit;
836                 goto match;
837             }
838         }
839         NOT_REACHED();
840
841     match: ;
842     }
843     return ds_steal_cstr(&s);
844 }
845
846 static enum ofputil_protocol
847 ofputil_protocol_from_string__(const char *s, size_t n)
848 {
849     const struct proto_abbrev *p;
850     int i;
851
852     for (i = 0; i < CHAR_BIT * sizeof(enum ofputil_protocol); i++) {
853         enum ofputil_protocol bit = 1u << i;
854         const char *name = ofputil_protocol_to_string(bit);
855
856         if (name && n == strlen(name) && !strncasecmp(s, name, n)) {
857             return bit;
858         }
859     }
860
861     for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
862         if (n == strlen(p->name) && !strncasecmp(s, p->name, n)) {
863             return p->protocol;
864         }
865     }
866
867     return 0;
868 }
869
870 /* Returns the nonempty set of protocols represented by 's', which can be a
871  * single protocol name or abbreviation or a comma-separated list of them.
872  *
873  * Aborts the program with an error message if 's' is invalid. */
874 enum ofputil_protocol
875 ofputil_protocols_from_string(const char *s)
876 {
877     const char *orig_s = s;
878     enum ofputil_protocol protocols;
879
880     protocols = 0;
881     while (*s) {
882         enum ofputil_protocol p;
883         size_t n;
884
885         n = strcspn(s, ",");
886         if (n == 0) {
887             s++;
888             continue;
889         }
890
891         p = ofputil_protocol_from_string__(s, n);
892         if (!p) {
893             ovs_fatal(0, "%.*s: unknown flow protocol", (int) n, s);
894         }
895         protocols |= p;
896
897         s += n;
898     }
899
900     if (!protocols) {
901         ovs_fatal(0, "%s: no flow protocol specified", orig_s);
902     }
903     return protocols;
904 }
905
906 static int
907 ofputil_version_from_string(const char *s)
908 {
909     if (!strcasecmp(s, "OpenFlow10")) {
910         return OFP10_VERSION;
911     }
912     if (!strcasecmp(s, "OpenFlow11")) {
913         return OFP11_VERSION;
914     }
915     if (!strcasecmp(s, "OpenFlow12")) {
916         return OFP12_VERSION;
917     }
918     if (!strcasecmp(s, "OpenFlow13")) {
919         return OFP13_VERSION;
920     }
921     return 0;
922 }
923
924 static bool
925 is_delimiter(unsigned char c)
926 {
927     return isspace(c) || c == ',';
928 }
929
930 uint32_t
931 ofputil_versions_from_string(const char *s)
932 {
933     size_t i = 0;
934     uint32_t bitmap = 0;
935
936     while (s[i]) {
937         size_t j;
938         int version;
939         char *key;
940
941         if (is_delimiter(s[i])) {
942             i++;
943             continue;
944         }
945         j = 0;
946         while (s[i + j] && !is_delimiter(s[i + j])) {
947             j++;
948         }
949         key = xmemdup0(s + i, j);
950         version = ofputil_version_from_string(key);
951         if (!version) {
952             VLOG_FATAL("Unknown OpenFlow version: \"%s\"", key);
953         }
954         free(key);
955         bitmap |= 1u << version;
956         i += j;
957     }
958
959     return bitmap;
960 }
961
962 uint32_t
963 ofputil_versions_from_strings(char ** const s, size_t count)
964 {
965     uint32_t bitmap = 0;
966
967     while (count--) {
968         int version = ofputil_version_from_string(s[count]);
969         if (!version) {
970             VLOG_WARN("Unknown OpenFlow version: \"%s\"", s[count]);
971         } else {
972             bitmap |= 1u << version;
973         }
974     }
975
976     return bitmap;
977 }
978
979 const char *
980 ofputil_version_to_string(enum ofp_version ofp_version)
981 {
982     switch (ofp_version) {
983     case OFP10_VERSION:
984         return "OpenFlow10";
985     case OFP11_VERSION:
986         return "OpenFlow11";
987     case OFP12_VERSION:
988         return "OpenFlow12";
989     case OFP13_VERSION:
990         return "OpenFlow13";
991     default:
992         NOT_REACHED();
993     }
994 }
995
996 bool
997 ofputil_packet_in_format_is_valid(enum nx_packet_in_format packet_in_format)
998 {
999     switch (packet_in_format) {
1000     case NXPIF_OPENFLOW10:
1001     case NXPIF_NXM:
1002         return true;
1003     }
1004
1005     return false;
1006 }
1007
1008 const char *
1009 ofputil_packet_in_format_to_string(enum nx_packet_in_format packet_in_format)
1010 {
1011     switch (packet_in_format) {
1012     case NXPIF_OPENFLOW10:
1013         return "openflow10";
1014     case NXPIF_NXM:
1015         return "nxm";
1016     default:
1017         NOT_REACHED();
1018     }
1019 }
1020
1021 int
1022 ofputil_packet_in_format_from_string(const char *s)
1023 {
1024     return (!strcmp(s, "openflow10") ? NXPIF_OPENFLOW10
1025             : !strcmp(s, "nxm") ? NXPIF_NXM
1026             : -1);
1027 }
1028
1029 static bool
1030 regs_fully_wildcarded(const struct flow_wildcards *wc)
1031 {
1032     int i;
1033
1034     for (i = 0; i < FLOW_N_REGS; i++) {
1035         if (wc->masks.regs[i] != 0) {
1036             return false;
1037         }
1038     }
1039     return true;
1040 }
1041
1042 /* Returns a bit-mask of ofputil_protocols that can be used for sending 'match'
1043  * to a switch (e.g. to add or remove a flow).  Only NXM can handle tunnel IDs,
1044  * registers, or fixing the Ethernet multicast bit.  Otherwise, it's better to
1045  * use OpenFlow 1.0 protocol for backward compatibility. */
1046 enum ofputil_protocol
1047 ofputil_usable_protocols(const struct match *match)
1048 {
1049     const struct flow_wildcards *wc = &match->wc;
1050
1051     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 20);
1052
1053     /* These tunnel params can't be sent in a flow_mod */
1054     if (wc->masks.tunnel.ip_ttl
1055         || wc->masks.tunnel.ip_tos || wc->masks.tunnel.flags) {
1056         return OFPUTIL_P_NONE;
1057     }
1058
1059     /* skb_mark and skb_priority can't be sent in a flow_mod */
1060     if (wc->masks.skb_mark || wc->masks.skb_priority) {
1061         return OFPUTIL_P_NONE;
1062     }
1063
1064     /* NXM, OXM, and OF1.1 support bitwise matching on ethernet addresses. */
1065     if (!eth_mask_is_exact(wc->masks.dl_src)
1066         && !eth_addr_is_zero(wc->masks.dl_src)) {
1067         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1068             | OFPUTIL_P_OF13_OXM;
1069     }
1070     if (!eth_mask_is_exact(wc->masks.dl_dst)
1071         && !eth_addr_is_zero(wc->masks.dl_dst)) {
1072         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1073             | OFPUTIL_P_OF13_OXM;
1074     }
1075
1076     /* NXM, OXM, and OF1.1+ support matching metadata. */
1077     if (wc->masks.metadata != htonll(0)) {
1078         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1079             | OFPUTIL_P_OF13_OXM;
1080     }
1081
1082     /* NXM and OXM support matching ARP hardware addresses. */
1083     if (!eth_addr_is_zero(wc->masks.arp_sha) ||
1084         !eth_addr_is_zero(wc->masks.arp_tha)) {
1085         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1086             | OFPUTIL_P_OF13_OXM;
1087     }
1088
1089     /* NXM and OXM support matching IPv6 traffic. */
1090     if (match->flow.dl_type == htons(ETH_TYPE_IPV6)) {
1091         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1092             | OFPUTIL_P_OF13_OXM;
1093     }
1094
1095     /* NXM and OXM support matching registers. */
1096     if (!regs_fully_wildcarded(wc)) {
1097         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1098             | OFPUTIL_P_OF13_OXM;
1099     }
1100
1101     /* NXM and OXM support matching tun_id, tun_src, and tun_dst. */
1102     if (wc->masks.tunnel.tun_id != htonll(0)
1103         || wc->masks.tunnel.ip_src != htonl(0)
1104         || wc->masks.tunnel.ip_dst != htonl(0)) {
1105         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1106             | OFPUTIL_P_OF13_OXM;
1107     }
1108
1109     /* NXM and OXM support matching fragments. */
1110     if (wc->masks.nw_frag) {
1111         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1112             | OFPUTIL_P_OF13_OXM;
1113     }
1114
1115     /* NXM and OXM support matching IPv6 flow label. */
1116     if (wc->masks.ipv6_label) {
1117         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1118             | OFPUTIL_P_OF13_OXM;
1119     }
1120
1121     /* NXM and OXM support matching IP ECN bits. */
1122     if (wc->masks.nw_tos & IP_ECN_MASK) {
1123         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1124             | OFPUTIL_P_OF13_OXM;
1125     }
1126
1127     /* NXM and OXM support matching IP TTL/hop limit. */
1128     if (wc->masks.nw_ttl) {
1129         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1130             | OFPUTIL_P_OF13_OXM;
1131     }
1132
1133     /* NXM and OXM support non-CIDR IPv4 address masks. */
1134     if (!ip_is_cidr(wc->masks.nw_src) || !ip_is_cidr(wc->masks.nw_dst)) {
1135         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1136             | OFPUTIL_P_OF13_OXM;
1137     }
1138
1139     /* NXM and OXM support bitwise matching on transport port. */
1140     if ((wc->masks.tp_src && wc->masks.tp_src != htons(UINT16_MAX)) ||
1141         (wc->masks.tp_dst && wc->masks.tp_dst != htons(UINT16_MAX))) {
1142         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1143             | OFPUTIL_P_OF13_OXM;
1144     }
1145
1146     /* NXM and OF1.1+ support matching MPLS label */
1147     if (wc->masks.mpls_lse & htonl(MPLS_LABEL_MASK)) {
1148         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1149             | OFPUTIL_P_OF13_OXM;
1150     }
1151
1152     /* NXM and OF1.1+ support matching MPLS TC */
1153     if (wc->masks.mpls_lse & htonl(MPLS_TC_MASK)) {
1154         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1155             | OFPUTIL_P_OF13_OXM;
1156     }
1157
1158     /* NXM and OF1.3+ support matching MPLS stack flag */
1159     /* Allow for OF1.2 as there doesn't seem to be a
1160      * particularly good reason not to */
1161     if (wc->masks.mpls_lse & htonl(MPLS_BOS_MASK)) {
1162         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1163             | OFPUTIL_P_OF13_OXM;
1164     }
1165
1166     /* Other formats can express this rule. */
1167     return OFPUTIL_P_ANY;
1168 }
1169
1170 void
1171 ofputil_format_version(struct ds *msg, enum ofp_version version)
1172 {
1173     ds_put_format(msg, "0x%02x", version);
1174 }
1175
1176 void
1177 ofputil_format_version_name(struct ds *msg, enum ofp_version version)
1178 {
1179     ds_put_cstr(msg, ofputil_version_to_string(version));
1180 }
1181
1182 static void
1183 ofputil_format_version_bitmap__(struct ds *msg, uint32_t bitmap,
1184                                 void (*format_version)(struct ds *msg,
1185                                                        enum ofp_version))
1186 {
1187     while (bitmap) {
1188         format_version(msg, raw_ctz(bitmap));
1189         bitmap = zero_rightmost_1bit(bitmap);
1190         if (bitmap) {
1191             ds_put_cstr(msg, ", ");
1192         }
1193     }
1194 }
1195
1196 void
1197 ofputil_format_version_bitmap(struct ds *msg, uint32_t bitmap)
1198 {
1199     ofputil_format_version_bitmap__(msg, bitmap, ofputil_format_version);
1200 }
1201
1202 void
1203 ofputil_format_version_bitmap_names(struct ds *msg, uint32_t bitmap)
1204 {
1205     ofputil_format_version_bitmap__(msg, bitmap, ofputil_format_version_name);
1206 }
1207
1208 static bool
1209 ofputil_decode_hello_bitmap(const struct ofp_hello_elem_header *oheh,
1210                             uint32_t *allowed_versionsp)
1211 {
1212     uint16_t bitmap_len = ntohs(oheh->length) - sizeof *oheh;
1213     const ovs_be32 *bitmap = (const ovs_be32 *) (oheh + 1);
1214     uint32_t allowed_versions;
1215
1216     if (!bitmap_len || bitmap_len % sizeof *bitmap) {
1217         return false;
1218     }
1219
1220     /* Only use the first 32-bit element of the bitmap as that is all the
1221      * current implementation supports.  Subsequent elements are ignored which
1222      * should have no effect on session negotiation until Open vSwtich supports
1223      * wire-protocol versions greater than 31.
1224      */
1225     allowed_versions = ntohl(bitmap[0]);
1226
1227     if (allowed_versions & 1) {
1228         /* There's no OpenFlow version 0. */
1229         VLOG_WARN_RL(&bad_ofmsg_rl, "peer claims to support invalid OpenFlow "
1230                      "version 0x00");
1231         allowed_versions &= ~1u;
1232     }
1233
1234     if (!allowed_versions) {
1235         VLOG_WARN_RL(&bad_ofmsg_rl, "peer does not support any OpenFlow "
1236                      "version (between 0x01 and 0x1f)");
1237         return false;
1238     }
1239
1240     *allowed_versionsp = allowed_versions;
1241     return true;
1242 }
1243
1244 static uint32_t
1245 version_bitmap_from_version(uint8_t ofp_version)
1246 {
1247     return ((ofp_version < 32 ? 1u << ofp_version : 0) - 1) << 1;
1248 }
1249
1250 /* Decodes OpenFlow OFPT_HELLO message 'oh', storing into '*allowed_versions'
1251  * the set of OpenFlow versions for which 'oh' announces support.
1252  *
1253  * Because of how OpenFlow defines OFPT_HELLO messages, this function is always
1254  * successful, and thus '*allowed_versions' is always initialized.  However, it
1255  * returns false if 'oh' contains some data that could not be fully understood,
1256  * true if 'oh' was completely parsed. */
1257 bool
1258 ofputil_decode_hello(const struct ofp_header *oh, uint32_t *allowed_versions)
1259 {
1260     struct ofpbuf msg;
1261     bool ok = true;
1262
1263     ofpbuf_use_const(&msg, oh, ntohs(oh->length));
1264     ofpbuf_pull(&msg, sizeof *oh);
1265
1266     *allowed_versions = version_bitmap_from_version(oh->version);
1267     while (msg.size) {
1268         const struct ofp_hello_elem_header *oheh;
1269         unsigned int len;
1270
1271         if (msg.size < sizeof *oheh) {
1272             return false;
1273         }
1274
1275         oheh = msg.data;
1276         len = ntohs(oheh->length);
1277         if (len < sizeof *oheh || !ofpbuf_try_pull(&msg, ROUND_UP(len, 8))) {
1278             return false;
1279         }
1280
1281         if (oheh->type != htons(OFPHET_VERSIONBITMAP)
1282             || !ofputil_decode_hello_bitmap(oheh, allowed_versions)) {
1283             ok = false;
1284         }
1285     }
1286
1287     return ok;
1288 }
1289
1290 /* Returns true if 'allowed_versions' needs to be accompanied by a version
1291  * bitmap to be correctly expressed in an OFPT_HELLO message. */
1292 static inline bool
1293 should_send_version_bitmap(uint32_t allowed_versions)
1294 {
1295     return !is_pow2((allowed_versions >> 1) + 1);
1296 }
1297
1298 /* Create an OFPT_HELLO message that expresses support for the OpenFlow
1299  * versions in the 'allowed_versions' bitmaps and returns the message. */
1300 struct ofpbuf *
1301 ofputil_encode_hello(uint32_t allowed_versions)
1302 {
1303     enum ofp_version ofp_version;
1304     struct ofpbuf *msg;
1305
1306     ofp_version = leftmost_1bit_idx(allowed_versions);
1307     msg = ofpraw_alloc(OFPRAW_OFPT_HELLO, ofp_version, 0);
1308
1309     if (should_send_version_bitmap(allowed_versions)) {
1310         struct ofp_hello_elem_header *oheh;
1311         uint16_t map_len;
1312
1313         map_len = sizeof allowed_versions;
1314         oheh = ofpbuf_put_zeros(msg, ROUND_UP(map_len + sizeof *oheh, 8));
1315         oheh->type = htons(OFPHET_VERSIONBITMAP);
1316         oheh->length = htons(map_len + sizeof *oheh);
1317         *(ovs_be32 *)(oheh + 1) = htonl(allowed_versions);
1318
1319         ofpmsg_update_length(msg);
1320     }
1321
1322     return msg;
1323 }
1324
1325 /* Returns an OpenFlow message that, sent on an OpenFlow connection whose
1326  * protocol is 'current', at least partly transitions the protocol to 'want'.
1327  * Stores in '*next' the protocol that will be in effect on the OpenFlow
1328  * connection if the switch processes the returned message correctly.  (If
1329  * '*next != want' then the caller will have to iterate.)
1330  *
1331  * If 'current == want', or if it is not possible to transition from 'current'
1332  * to 'want' (because, for example, 'current' and 'want' use different OpenFlow
1333  * protocol versions), returns NULL and stores 'current' in '*next'. */
1334 struct ofpbuf *
1335 ofputil_encode_set_protocol(enum ofputil_protocol current,
1336                             enum ofputil_protocol want,
1337                             enum ofputil_protocol *next)
1338 {
1339     enum ofp_version cur_version, want_version;
1340     enum ofputil_protocol cur_base, want_base;
1341     bool cur_tid, want_tid;
1342
1343     cur_version = ofputil_protocol_to_ofp_version(current);
1344     want_version = ofputil_protocol_to_ofp_version(want);
1345     if (cur_version != want_version) {
1346         *next = current;
1347         return NULL;
1348     }
1349
1350     cur_base = ofputil_protocol_to_base(current);
1351     want_base = ofputil_protocol_to_base(want);
1352     if (cur_base != want_base) {
1353         *next = ofputil_protocol_set_base(current, want_base);
1354
1355         switch (want_base) {
1356         case OFPUTIL_P_OF10_NXM:
1357             return ofputil_encode_nx_set_flow_format(NXFF_NXM);
1358
1359         case OFPUTIL_P_OF10_STD:
1360             return ofputil_encode_nx_set_flow_format(NXFF_OPENFLOW10);
1361
1362         case OFPUTIL_P_OF12_OXM:
1363         case OFPUTIL_P_OF13_OXM:
1364             /* There are only one of each OpenFlow 1.2+ protocols and we already
1365              * verified above that we're not trying to change versions. */
1366             NOT_REACHED();
1367
1368         case OFPUTIL_P_OF10_STD_TID:
1369         case OFPUTIL_P_OF10_NXM_TID:
1370             NOT_REACHED();
1371         }
1372     }
1373
1374     cur_tid = (current & OFPUTIL_P_TID) != 0;
1375     want_tid = (want & OFPUTIL_P_TID) != 0;
1376     if (cur_tid != want_tid) {
1377         *next = ofputil_protocol_set_tid(current, want_tid);
1378         return ofputil_make_flow_mod_table_id(want_tid);
1379     }
1380
1381     ovs_assert(current == want);
1382
1383     *next = current;
1384     return NULL;
1385 }
1386
1387 /* Returns an NXT_SET_FLOW_FORMAT message that can be used to set the flow
1388  * format to 'nxff'.  */
1389 struct ofpbuf *
1390 ofputil_encode_nx_set_flow_format(enum nx_flow_format nxff)
1391 {
1392     struct nx_set_flow_format *sff;
1393     struct ofpbuf *msg;
1394
1395     ovs_assert(ofputil_nx_flow_format_is_valid(nxff));
1396
1397     msg = ofpraw_alloc(OFPRAW_NXT_SET_FLOW_FORMAT, OFP10_VERSION, 0);
1398     sff = ofpbuf_put_zeros(msg, sizeof *sff);
1399     sff->format = htonl(nxff);
1400
1401     return msg;
1402 }
1403
1404 /* Returns the base protocol if 'flow_format' is a valid NXFF_* value, false
1405  * otherwise. */
1406 enum ofputil_protocol
1407 ofputil_nx_flow_format_to_protocol(enum nx_flow_format flow_format)
1408 {
1409     switch (flow_format) {
1410     case NXFF_OPENFLOW10:
1411         return OFPUTIL_P_OF10_STD;
1412
1413     case NXFF_NXM:
1414         return OFPUTIL_P_OF10_NXM;
1415
1416     default:
1417         return 0;
1418     }
1419 }
1420
1421 /* Returns true if 'flow_format' is a valid NXFF_* value, false otherwise. */
1422 bool
1423 ofputil_nx_flow_format_is_valid(enum nx_flow_format flow_format)
1424 {
1425     return ofputil_nx_flow_format_to_protocol(flow_format) != 0;
1426 }
1427
1428 /* Returns a string version of 'flow_format', which must be a valid NXFF_*
1429  * value. */
1430 const char *
1431 ofputil_nx_flow_format_to_string(enum nx_flow_format flow_format)
1432 {
1433     switch (flow_format) {
1434     case NXFF_OPENFLOW10:
1435         return "openflow10";
1436     case NXFF_NXM:
1437         return "nxm";
1438     default:
1439         NOT_REACHED();
1440     }
1441 }
1442
1443 struct ofpbuf *
1444 ofputil_make_set_packet_in_format(enum ofp_version ofp_version,
1445                                   enum nx_packet_in_format packet_in_format)
1446 {
1447     struct nx_set_packet_in_format *spif;
1448     struct ofpbuf *msg;
1449
1450     msg = ofpraw_alloc(OFPRAW_NXT_SET_PACKET_IN_FORMAT, ofp_version, 0);
1451     spif = ofpbuf_put_zeros(msg, sizeof *spif);
1452     spif->format = htonl(packet_in_format);
1453
1454     return msg;
1455 }
1456
1457 /* Returns an OpenFlow message that can be used to turn the flow_mod_table_id
1458  * extension on or off (according to 'flow_mod_table_id'). */
1459 struct ofpbuf *
1460 ofputil_make_flow_mod_table_id(bool flow_mod_table_id)
1461 {
1462     struct nx_flow_mod_table_id *nfmti;
1463     struct ofpbuf *msg;
1464
1465     msg = ofpraw_alloc(OFPRAW_NXT_FLOW_MOD_TABLE_ID, OFP10_VERSION, 0);
1466     nfmti = ofpbuf_put_zeros(msg, sizeof *nfmti);
1467     nfmti->set = flow_mod_table_id;
1468     return msg;
1469 }
1470
1471 /* Converts an OFPT_FLOW_MOD or NXT_FLOW_MOD message 'oh' into an abstract
1472  * flow_mod in 'fm'.  Returns 0 if successful, otherwise an OpenFlow error
1473  * code.
1474  *
1475  * Uses 'ofpacts' to store the abstract OFPACT_* version of 'oh''s actions.
1476  * The caller must initialize 'ofpacts' and retains ownership of it.
1477  * 'fm->ofpacts' will point into the 'ofpacts' buffer.
1478  *
1479  * Does not validate the flow_mod actions.  The caller should do that, with
1480  * ofpacts_check(). */
1481 enum ofperr
1482 ofputil_decode_flow_mod(struct ofputil_flow_mod *fm,
1483                         const struct ofp_header *oh,
1484                         enum ofputil_protocol protocol,
1485                         struct ofpbuf *ofpacts)
1486 {
1487     uint16_t command;
1488     struct ofpbuf b;
1489     enum ofpraw raw;
1490
1491     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1492     raw = ofpraw_pull_assert(&b);
1493     if (raw == OFPRAW_OFPT11_FLOW_MOD) {
1494         /* Standard OpenFlow 1.1 flow_mod. */
1495         const struct ofp11_flow_mod *ofm;
1496         enum ofperr error;
1497
1498         ofm = ofpbuf_pull(&b, sizeof *ofm);
1499
1500         error = ofputil_pull_ofp11_match(&b, &fm->match, NULL);
1501         if (error) {
1502             return error;
1503         }
1504
1505         error = ofpacts_pull_openflow11_instructions(&b, b.size, ofm->table_id,
1506                                                      ofpacts);
1507         if (error) {
1508             return error;
1509         }
1510
1511         /* Translate the message. */
1512         fm->priority = ntohs(ofm->priority);
1513         if (ofm->command == OFPFC_ADD) {
1514             fm->cookie = htonll(0);
1515             fm->cookie_mask = htonll(0);
1516             fm->new_cookie = ofm->cookie;
1517         } else {
1518             fm->cookie = ofm->cookie;
1519             fm->cookie_mask = ofm->cookie_mask;
1520             fm->new_cookie = htonll(UINT64_MAX);
1521         }
1522         fm->command = ofm->command;
1523         fm->table_id = ofm->table_id;
1524         fm->idle_timeout = ntohs(ofm->idle_timeout);
1525         fm->hard_timeout = ntohs(ofm->hard_timeout);
1526         fm->buffer_id = ntohl(ofm->buffer_id);
1527         error = ofputil_port_from_ofp11(ofm->out_port, &fm->out_port);
1528         if (error) {
1529             return error;
1530         }
1531         if ((ofm->command == OFPFC_DELETE
1532              || ofm->command == OFPFC_DELETE_STRICT)
1533             && ofm->out_group != htonl(OFPG_ANY)) {
1534             return OFPERR_OFPFMFC_UNKNOWN;
1535         }
1536         fm->flags = ntohs(ofm->flags);
1537     } else {
1538         if (raw == OFPRAW_OFPT10_FLOW_MOD) {
1539             /* Standard OpenFlow 1.0 flow_mod. */
1540             const struct ofp10_flow_mod *ofm;
1541             enum ofperr error;
1542
1543             /* Get the ofp10_flow_mod. */
1544             ofm = ofpbuf_pull(&b, sizeof *ofm);
1545
1546             /* Translate the rule. */
1547             ofputil_match_from_ofp10_match(&ofm->match, &fm->match);
1548             ofputil_normalize_match(&fm->match);
1549
1550             /* Now get the actions. */
1551             error = ofpacts_pull_openflow10(&b, b.size, ofpacts);
1552             if (error) {
1553                 return error;
1554             }
1555
1556             /* OpenFlow 1.0 says that exact-match rules have to have the
1557              * highest possible priority. */
1558             fm->priority = (ofm->match.wildcards & htonl(OFPFW10_ALL)
1559                             ? ntohs(ofm->priority)
1560                             : UINT16_MAX);
1561
1562             /* Translate the message. */
1563             command = ntohs(ofm->command);
1564             fm->cookie = htonll(0);
1565             fm->cookie_mask = htonll(0);
1566             fm->new_cookie = ofm->cookie;
1567             fm->idle_timeout = ntohs(ofm->idle_timeout);
1568             fm->hard_timeout = ntohs(ofm->hard_timeout);
1569             fm->buffer_id = ntohl(ofm->buffer_id);
1570             fm->out_port = ntohs(ofm->out_port);
1571             fm->flags = ntohs(ofm->flags);
1572         } else if (raw == OFPRAW_NXT_FLOW_MOD) {
1573             /* Nicira extended flow_mod. */
1574             const struct nx_flow_mod *nfm;
1575             enum ofperr error;
1576
1577             /* Dissect the message. */
1578             nfm = ofpbuf_pull(&b, sizeof *nfm);
1579             error = nx_pull_match(&b, ntohs(nfm->match_len),
1580                                   &fm->match, &fm->cookie, &fm->cookie_mask);
1581             if (error) {
1582                 return error;
1583             }
1584             error = ofpacts_pull_openflow10(&b, b.size, ofpacts);
1585             if (error) {
1586                 return error;
1587             }
1588
1589             /* Translate the message. */
1590             command = ntohs(nfm->command);
1591             if ((command & 0xff) == OFPFC_ADD && fm->cookie_mask) {
1592                 /* Flow additions may only set a new cookie, not match an
1593                  * existing cookie. */
1594                 return OFPERR_NXBRC_NXM_INVALID;
1595             }
1596             fm->priority = ntohs(nfm->priority);
1597             fm->new_cookie = nfm->cookie;
1598             fm->idle_timeout = ntohs(nfm->idle_timeout);
1599             fm->hard_timeout = ntohs(nfm->hard_timeout);
1600             fm->buffer_id = ntohl(nfm->buffer_id);
1601             fm->out_port = ntohs(nfm->out_port);
1602             fm->flags = ntohs(nfm->flags);
1603         } else {
1604             NOT_REACHED();
1605         }
1606
1607         if (fm->flags & OFPFF10_EMERG) {
1608             /* We do not support the OpenFlow 1.0 emergency flow cache, which
1609              * is not required in OpenFlow 1.0.1 and removed from OpenFlow 1.1.
1610              *
1611              * OpenFlow 1.0 specifies the error code to use when idle_timeout
1612              * or hard_timeout is nonzero.  Otherwise, there is no good error
1613              * code, so just state that the flow table is full. */
1614             return (fm->hard_timeout || fm->idle_timeout
1615                     ? OFPERR_OFPFMFC_BAD_EMERG_TIMEOUT
1616                     : OFPERR_OFPFMFC_TABLE_FULL);
1617         }
1618
1619         if (protocol & OFPUTIL_P_TID) {
1620             fm->command = command & 0xff;
1621             fm->table_id = command >> 8;
1622         } else {
1623             fm->command = command;
1624             fm->table_id = 0xff;
1625         }
1626     }
1627
1628     fm->ofpacts = ofpacts->data;
1629     fm->ofpacts_len = ofpacts->size;
1630
1631     return 0;
1632 }
1633
1634 static ovs_be16
1635 ofputil_tid_command(const struct ofputil_flow_mod *fm,
1636                     enum ofputil_protocol protocol)
1637 {
1638     return htons(protocol & OFPUTIL_P_TID
1639                  ? (fm->command & 0xff) | (fm->table_id << 8)
1640                  : fm->command);
1641 }
1642
1643 /* Converts 'fm' into an OFPT_FLOW_MOD or NXT_FLOW_MOD message according to
1644  * 'protocol' and returns the message. */
1645 struct ofpbuf *
1646 ofputil_encode_flow_mod(const struct ofputil_flow_mod *fm,
1647                         enum ofputil_protocol protocol)
1648 {
1649     struct ofpbuf *msg;
1650
1651     switch (protocol) {
1652     case OFPUTIL_P_OF12_OXM:
1653     case OFPUTIL_P_OF13_OXM: {
1654         struct ofp11_flow_mod *ofm;
1655
1656         msg = ofpraw_alloc(OFPRAW_OFPT11_FLOW_MOD, 
1657                            ofputil_protocol_to_ofp_version(protocol),
1658                            NXM_TYPICAL_LEN + fm->ofpacts_len);
1659         ofm = ofpbuf_put_zeros(msg, sizeof *ofm);
1660         if (fm->command == OFPFC_ADD) {
1661             ofm->cookie = fm->new_cookie;
1662         } else {
1663             ofm->cookie = fm->cookie;
1664         }
1665         ofm->cookie_mask = fm->cookie_mask;
1666         ofm->table_id = fm->table_id;
1667         ofm->command = fm->command;
1668         ofm->idle_timeout = htons(fm->idle_timeout);
1669         ofm->hard_timeout = htons(fm->hard_timeout);
1670         ofm->priority = htons(fm->priority);
1671         ofm->buffer_id = htonl(fm->buffer_id);
1672         ofm->out_port = ofputil_port_to_ofp11(fm->out_port);
1673         ofm->out_group = htonl(OFPG11_ANY);
1674         ofm->flags = htons(fm->flags);
1675         oxm_put_match(msg, &fm->match);
1676         ofpacts_put_openflow11_instructions(fm->ofpacts, fm->ofpacts_len, msg);
1677         break;
1678     }
1679
1680     case OFPUTIL_P_OF10_STD:
1681     case OFPUTIL_P_OF10_STD_TID: {
1682         struct ofp10_flow_mod *ofm;
1683
1684         msg = ofpraw_alloc(OFPRAW_OFPT10_FLOW_MOD, OFP10_VERSION,
1685                            fm->ofpacts_len);
1686         ofm = ofpbuf_put_zeros(msg, sizeof *ofm);
1687         ofputil_match_to_ofp10_match(&fm->match, &ofm->match);
1688         ofm->cookie = fm->new_cookie;
1689         ofm->command = ofputil_tid_command(fm, protocol);
1690         ofm->idle_timeout = htons(fm->idle_timeout);
1691         ofm->hard_timeout = htons(fm->hard_timeout);
1692         ofm->priority = htons(fm->priority);
1693         ofm->buffer_id = htonl(fm->buffer_id);
1694         ofm->out_port = htons(fm->out_port);
1695         ofm->flags = htons(fm->flags);
1696         ofpacts_put_openflow10(fm->ofpacts, fm->ofpacts_len, msg);
1697         break;
1698     }
1699
1700     case OFPUTIL_P_OF10_NXM:
1701     case OFPUTIL_P_OF10_NXM_TID: {
1702         struct nx_flow_mod *nfm;
1703         int match_len;
1704
1705         msg = ofpraw_alloc(OFPRAW_NXT_FLOW_MOD, OFP10_VERSION,
1706                            NXM_TYPICAL_LEN + fm->ofpacts_len);
1707         nfm = ofpbuf_put_zeros(msg, sizeof *nfm);
1708         nfm->command = ofputil_tid_command(fm, protocol);
1709         nfm->cookie = fm->new_cookie;
1710         match_len = nx_put_match(msg, &fm->match, fm->cookie, fm->cookie_mask);
1711         nfm = msg->l3;
1712         nfm->idle_timeout = htons(fm->idle_timeout);
1713         nfm->hard_timeout = htons(fm->hard_timeout);
1714         nfm->priority = htons(fm->priority);
1715         nfm->buffer_id = htonl(fm->buffer_id);
1716         nfm->out_port = htons(fm->out_port);
1717         nfm->flags = htons(fm->flags);
1718         nfm->match_len = htons(match_len);
1719         ofpacts_put_openflow10(fm->ofpacts, fm->ofpacts_len, msg);
1720         break;
1721     }
1722
1723     default:
1724         NOT_REACHED();
1725     }
1726
1727     ofpmsg_update_length(msg);
1728     return msg;
1729 }
1730
1731 /* Returns a bitmask with a 1-bit for each protocol that could be used to
1732  * send all of the 'n_fm's flow table modification requests in 'fms', and a
1733  * 0-bit for each protocol that is inadequate.
1734  *
1735  * (The return value will have at least one 1-bit.) */
1736 enum ofputil_protocol
1737 ofputil_flow_mod_usable_protocols(const struct ofputil_flow_mod *fms,
1738                                   size_t n_fms)
1739 {
1740     enum ofputil_protocol usable_protocols;
1741     size_t i;
1742
1743     usable_protocols = OFPUTIL_P_ANY;
1744     for (i = 0; i < n_fms; i++) {
1745         const struct ofputil_flow_mod *fm = &fms[i];
1746
1747         usable_protocols &= ofputil_usable_protocols(&fm->match);
1748         if (fm->table_id != 0xff) {
1749             usable_protocols &= OFPUTIL_P_TID;
1750         }
1751
1752         /* Matching of the cookie is only supported through NXM or OF1.1+. */
1753         if (fm->cookie_mask != htonll(0)) {
1754             usable_protocols &= OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1755                 | OFPUTIL_P_OF13_OXM;
1756         }
1757     }
1758
1759     return usable_protocols;
1760 }
1761
1762 static enum ofperr
1763 ofputil_decode_ofpst10_flow_request(struct ofputil_flow_stats_request *fsr,
1764                                     const struct ofp10_flow_stats_request *ofsr,
1765                                     bool aggregate)
1766 {
1767     fsr->aggregate = aggregate;
1768     ofputil_match_from_ofp10_match(&ofsr->match, &fsr->match);
1769     fsr->out_port = ntohs(ofsr->out_port);
1770     fsr->table_id = ofsr->table_id;
1771     fsr->cookie = fsr->cookie_mask = htonll(0);
1772
1773     return 0;
1774 }
1775
1776 static enum ofperr
1777 ofputil_decode_ofpst11_flow_request(struct ofputil_flow_stats_request *fsr,
1778                                     struct ofpbuf *b, bool aggregate)
1779 {
1780     const struct ofp11_flow_stats_request *ofsr;
1781     enum ofperr error;
1782
1783     ofsr = ofpbuf_pull(b, sizeof *ofsr);
1784     fsr->aggregate = aggregate;
1785     fsr->table_id = ofsr->table_id;
1786     error = ofputil_port_from_ofp11(ofsr->out_port, &fsr->out_port);
1787     if (error) {
1788         return error;
1789     }
1790     if (ofsr->out_group != htonl(OFPG11_ANY)) {
1791         return OFPERR_OFPFMFC_UNKNOWN;
1792     }
1793     fsr->cookie = ofsr->cookie;
1794     fsr->cookie_mask = ofsr->cookie_mask;
1795     error = ofputil_pull_ofp11_match(b, &fsr->match, NULL);
1796     if (error) {
1797         return error;
1798     }
1799
1800     return 0;
1801 }
1802
1803 static enum ofperr
1804 ofputil_decode_nxst_flow_request(struct ofputil_flow_stats_request *fsr,
1805                                  struct ofpbuf *b, bool aggregate)
1806 {
1807     const struct nx_flow_stats_request *nfsr;
1808     enum ofperr error;
1809
1810     nfsr = ofpbuf_pull(b, sizeof *nfsr);
1811     error = nx_pull_match(b, ntohs(nfsr->match_len), &fsr->match,
1812                           &fsr->cookie, &fsr->cookie_mask);
1813     if (error) {
1814         return error;
1815     }
1816     if (b->size) {
1817         return OFPERR_OFPBRC_BAD_LEN;
1818     }
1819
1820     fsr->aggregate = aggregate;
1821     fsr->out_port = ntohs(nfsr->out_port);
1822     fsr->table_id = nfsr->table_id;
1823
1824     return 0;
1825 }
1826
1827 /* Converts an OFPST_FLOW, OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE
1828  * request 'oh', into an abstract flow_stats_request in 'fsr'.  Returns 0 if
1829  * successful, otherwise an OpenFlow error code. */
1830 enum ofperr
1831 ofputil_decode_flow_stats_request(struct ofputil_flow_stats_request *fsr,
1832                                   const struct ofp_header *oh)
1833 {
1834     enum ofpraw raw;
1835     struct ofpbuf b;
1836
1837     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1838     raw = ofpraw_pull_assert(&b);
1839     switch ((int) raw) {
1840     case OFPRAW_OFPST10_FLOW_REQUEST:
1841         return ofputil_decode_ofpst10_flow_request(fsr, b.data, false);
1842
1843     case OFPRAW_OFPST10_AGGREGATE_REQUEST:
1844         return ofputil_decode_ofpst10_flow_request(fsr, b.data, true);
1845
1846     case OFPRAW_OFPST11_FLOW_REQUEST:
1847         return ofputil_decode_ofpst11_flow_request(fsr, &b, false);
1848
1849     case OFPRAW_OFPST11_AGGREGATE_REQUEST:
1850         return ofputil_decode_ofpst11_flow_request(fsr, &b, true);
1851
1852     case OFPRAW_NXST_FLOW_REQUEST:
1853         return ofputil_decode_nxst_flow_request(fsr, &b, false);
1854
1855     case OFPRAW_NXST_AGGREGATE_REQUEST:
1856         return ofputil_decode_nxst_flow_request(fsr, &b, true);
1857
1858     default:
1859         /* Hey, the caller lied. */
1860         NOT_REACHED();
1861     }
1862 }
1863
1864 /* Converts abstract flow_stats_request 'fsr' into an OFPST_FLOW,
1865  * OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE request 'oh' according to
1866  * 'protocol', and returns the message. */
1867 struct ofpbuf *
1868 ofputil_encode_flow_stats_request(const struct ofputil_flow_stats_request *fsr,
1869                                   enum ofputil_protocol protocol)
1870 {
1871     struct ofpbuf *msg;
1872     enum ofpraw raw;
1873
1874     switch (protocol) {
1875     case OFPUTIL_P_OF12_OXM:
1876     case OFPUTIL_P_OF13_OXM: {
1877         struct ofp11_flow_stats_request *ofsr;
1878
1879         raw = (fsr->aggregate
1880                ? OFPRAW_OFPST11_AGGREGATE_REQUEST
1881                : OFPRAW_OFPST11_FLOW_REQUEST);
1882         msg = ofpraw_alloc(raw, ofputil_protocol_to_ofp_version(protocol),
1883                            NXM_TYPICAL_LEN);
1884         ofsr = ofpbuf_put_zeros(msg, sizeof *ofsr);
1885         ofsr->table_id = fsr->table_id;
1886         ofsr->out_port = ofputil_port_to_ofp11(fsr->out_port);
1887         ofsr->out_group = htonl(OFPG11_ANY);
1888         ofsr->cookie = fsr->cookie;
1889         ofsr->cookie_mask = fsr->cookie_mask;
1890         oxm_put_match(msg, &fsr->match);
1891         break;
1892     }
1893
1894     case OFPUTIL_P_OF10_STD:
1895     case OFPUTIL_P_OF10_STD_TID: {
1896         struct ofp10_flow_stats_request *ofsr;
1897
1898         raw = (fsr->aggregate
1899                ? OFPRAW_OFPST10_AGGREGATE_REQUEST
1900                : OFPRAW_OFPST10_FLOW_REQUEST);
1901         msg = ofpraw_alloc(raw, OFP10_VERSION, 0);
1902         ofsr = ofpbuf_put_zeros(msg, sizeof *ofsr);
1903         ofputil_match_to_ofp10_match(&fsr->match, &ofsr->match);
1904         ofsr->table_id = fsr->table_id;
1905         ofsr->out_port = htons(fsr->out_port);
1906         break;
1907     }
1908
1909     case OFPUTIL_P_OF10_NXM:
1910     case OFPUTIL_P_OF10_NXM_TID: {
1911         struct nx_flow_stats_request *nfsr;
1912         int match_len;
1913
1914         raw = (fsr->aggregate
1915                ? OFPRAW_NXST_AGGREGATE_REQUEST
1916                : OFPRAW_NXST_FLOW_REQUEST);
1917         msg = ofpraw_alloc(raw, OFP10_VERSION, NXM_TYPICAL_LEN);
1918         ofpbuf_put_zeros(msg, sizeof *nfsr);
1919         match_len = nx_put_match(msg, &fsr->match,
1920                                  fsr->cookie, fsr->cookie_mask);
1921
1922         nfsr = msg->l3;
1923         nfsr->out_port = htons(fsr->out_port);
1924         nfsr->match_len = htons(match_len);
1925         nfsr->table_id = fsr->table_id;
1926         break;
1927     }
1928
1929     default:
1930         NOT_REACHED();
1931     }
1932
1933     return msg;
1934 }
1935
1936 /* Returns a bitmask with a 1-bit for each protocol that could be used to
1937  * accurately encode 'fsr', and a 0-bit for each protocol that is inadequate.
1938  *
1939  * (The return value will have at least one 1-bit.) */
1940 enum ofputil_protocol
1941 ofputil_flow_stats_request_usable_protocols(
1942     const struct ofputil_flow_stats_request *fsr)
1943 {
1944     enum ofputil_protocol usable_protocols;
1945
1946     usable_protocols = ofputil_usable_protocols(&fsr->match);
1947     if (fsr->cookie_mask != htonll(0)) {
1948         usable_protocols &= OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1949             | OFPUTIL_P_OF13_OXM;
1950     }
1951     return usable_protocols;
1952 }
1953
1954 /* Converts an OFPST_FLOW or NXST_FLOW reply in 'msg' into an abstract
1955  * ofputil_flow_stats in 'fs'.
1956  *
1957  * Multiple OFPST_FLOW or NXST_FLOW replies can be packed into a single
1958  * OpenFlow message.  Calling this function multiple times for a single 'msg'
1959  * iterates through the replies.  The caller must initially leave 'msg''s layer
1960  * pointers null and not modify them between calls.
1961  *
1962  * Most switches don't send the values needed to populate fs->idle_age and
1963  * fs->hard_age, so those members will usually be set to 0.  If the switch from
1964  * which 'msg' originated is known to implement NXT_FLOW_AGE, then pass
1965  * 'flow_age_extension' as true so that the contents of 'msg' determine the
1966  * 'idle_age' and 'hard_age' members in 'fs'.
1967  *
1968  * Uses 'ofpacts' to store the abstract OFPACT_* version of the flow stats
1969  * reply's actions.  The caller must initialize 'ofpacts' and retains ownership
1970  * of it.  'fs->ofpacts' will point into the 'ofpacts' buffer.
1971  *
1972  * Returns 0 if successful, EOF if no replies were left in this 'msg',
1973  * otherwise a positive errno value. */
1974 int
1975 ofputil_decode_flow_stats_reply(struct ofputil_flow_stats *fs,
1976                                 struct ofpbuf *msg,
1977                                 bool flow_age_extension,
1978                                 struct ofpbuf *ofpacts)
1979 {
1980     enum ofperr error;
1981     enum ofpraw raw;
1982
1983     error = (msg->l2
1984              ? ofpraw_decode(&raw, msg->l2)
1985              : ofpraw_pull(&raw, msg));
1986     if (error) {
1987         return error;
1988     }
1989
1990     if (!msg->size) {
1991         return EOF;
1992     } else if (raw == OFPRAW_OFPST11_FLOW_REPLY
1993                || raw == OFPRAW_OFPST13_FLOW_REPLY) {
1994         const struct ofp11_flow_stats *ofs;
1995         size_t length;
1996         uint16_t padded_match_len;
1997
1998         ofs = ofpbuf_try_pull(msg, sizeof *ofs);
1999         if (!ofs) {
2000             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply has %zu leftover "
2001                          "bytes at end", msg->size);
2002             return EINVAL;
2003         }
2004
2005         length = ntohs(ofs->length);
2006         if (length < sizeof *ofs) {
2007             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply claims invalid "
2008                          "length %zu", length);
2009             return EINVAL;
2010         }
2011
2012         if (ofputil_pull_ofp11_match(msg, &fs->match, &padded_match_len)) {
2013             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply bad match");
2014             return EINVAL;
2015         }
2016
2017         if (ofpacts_pull_openflow11_instructions(msg, length - sizeof *ofs -
2018                                                  padded_match_len,
2019                                                  ofs->table_id, ofpacts)) {
2020             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply bad instructions");
2021             return EINVAL;
2022         }
2023
2024         fs->priority = ntohs(ofs->priority);
2025         fs->table_id = ofs->table_id;
2026         fs->duration_sec = ntohl(ofs->duration_sec);
2027         fs->duration_nsec = ntohl(ofs->duration_nsec);
2028         fs->idle_timeout = ntohs(ofs->idle_timeout);
2029         fs->hard_timeout = ntohs(ofs->hard_timeout);
2030         fs->flags = (raw == OFPRAW_OFPST13_FLOW_REPLY) ? ntohs(ofs->flags) : 0;
2031         fs->idle_age = -1;
2032         fs->hard_age = -1;
2033         fs->cookie = ofs->cookie;
2034         fs->packet_count = ntohll(ofs->packet_count);
2035         fs->byte_count = ntohll(ofs->byte_count);
2036     } else if (raw == OFPRAW_OFPST10_FLOW_REPLY) {
2037         const struct ofp10_flow_stats *ofs;
2038         size_t length;
2039
2040         ofs = ofpbuf_try_pull(msg, sizeof *ofs);
2041         if (!ofs) {
2042             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply has %zu leftover "
2043                          "bytes at end", msg->size);
2044             return EINVAL;
2045         }
2046
2047         length = ntohs(ofs->length);
2048         if (length < sizeof *ofs) {
2049             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply claims invalid "
2050                          "length %zu", length);
2051             return EINVAL;
2052         }
2053
2054         if (ofpacts_pull_openflow10(msg, length - sizeof *ofs, ofpacts)) {
2055             return EINVAL;
2056         }
2057
2058         fs->cookie = get_32aligned_be64(&ofs->cookie);
2059         ofputil_match_from_ofp10_match(&ofs->match, &fs->match);
2060         fs->priority = ntohs(ofs->priority);
2061         fs->table_id = ofs->table_id;
2062         fs->duration_sec = ntohl(ofs->duration_sec);
2063         fs->duration_nsec = ntohl(ofs->duration_nsec);
2064         fs->idle_timeout = ntohs(ofs->idle_timeout);
2065         fs->hard_timeout = ntohs(ofs->hard_timeout);
2066         fs->idle_age = -1;
2067         fs->hard_age = -1;
2068         fs->packet_count = ntohll(get_32aligned_be64(&ofs->packet_count));
2069         fs->byte_count = ntohll(get_32aligned_be64(&ofs->byte_count));
2070         fs->flags = 0;
2071     } else if (raw == OFPRAW_NXST_FLOW_REPLY) {
2072         const struct nx_flow_stats *nfs;
2073         size_t match_len, actions_len, length;
2074
2075         nfs = ofpbuf_try_pull(msg, sizeof *nfs);
2076         if (!nfs) {
2077             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply has %zu leftover "
2078                          "bytes at end", msg->size);
2079             return EINVAL;
2080         }
2081
2082         length = ntohs(nfs->length);
2083         match_len = ntohs(nfs->match_len);
2084         if (length < sizeof *nfs + ROUND_UP(match_len, 8)) {
2085             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply with match_len=%zu "
2086                          "claims invalid length %zu", match_len, length);
2087             return EINVAL;
2088         }
2089         if (nx_pull_match(msg, match_len, &fs->match, NULL, NULL)) {
2090             return EINVAL;
2091         }
2092
2093         actions_len = length - sizeof *nfs - ROUND_UP(match_len, 8);
2094         if (ofpacts_pull_openflow10(msg, actions_len, ofpacts)) {
2095             return EINVAL;
2096         }
2097
2098         fs->cookie = nfs->cookie;
2099         fs->table_id = nfs->table_id;
2100         fs->duration_sec = ntohl(nfs->duration_sec);
2101         fs->duration_nsec = ntohl(nfs->duration_nsec);
2102         fs->priority = ntohs(nfs->priority);
2103         fs->idle_timeout = ntohs(nfs->idle_timeout);
2104         fs->hard_timeout = ntohs(nfs->hard_timeout);
2105         fs->idle_age = -1;
2106         fs->hard_age = -1;
2107         if (flow_age_extension) {
2108             if (nfs->idle_age) {
2109                 fs->idle_age = ntohs(nfs->idle_age) - 1;
2110             }
2111             if (nfs->hard_age) {
2112                 fs->hard_age = ntohs(nfs->hard_age) - 1;
2113             }
2114         }
2115         fs->packet_count = ntohll(nfs->packet_count);
2116         fs->byte_count = ntohll(nfs->byte_count);
2117         fs->flags = 0;
2118     } else {
2119         NOT_REACHED();
2120     }
2121
2122     fs->ofpacts = ofpacts->data;
2123     fs->ofpacts_len = ofpacts->size;
2124
2125     return 0;
2126 }
2127
2128 /* Returns 'count' unchanged except that UINT64_MAX becomes 0.
2129  *
2130  * We use this in situations where OVS internally uses UINT64_MAX to mean
2131  * "value unknown" but OpenFlow 1.0 does not define any unknown value. */
2132 static uint64_t
2133 unknown_to_zero(uint64_t count)
2134 {
2135     return count != UINT64_MAX ? count : 0;
2136 }
2137
2138 /* Appends an OFPST_FLOW or NXST_FLOW reply that contains the data in 'fs' to
2139  * those already present in the list of ofpbufs in 'replies'.  'replies' should
2140  * have been initialized with ofputil_start_stats_reply(). */
2141 void
2142 ofputil_append_flow_stats_reply(const struct ofputil_flow_stats *fs,
2143                                 struct list *replies)
2144 {
2145     struct ofpbuf *reply = ofpbuf_from_list(list_back(replies));
2146     size_t start_ofs = reply->size;
2147     enum ofpraw raw;
2148
2149     ofpraw_decode_partial(&raw, reply->data, reply->size);
2150     if (raw == OFPRAW_OFPST11_FLOW_REPLY || raw == OFPRAW_OFPST13_FLOW_REPLY) {
2151         struct ofp11_flow_stats *ofs;
2152
2153         ofpbuf_put_uninit(reply, sizeof *ofs);
2154         oxm_put_match(reply, &fs->match);
2155         ofpacts_put_openflow11_instructions(fs->ofpacts, fs->ofpacts_len,
2156                                             reply);
2157
2158         ofs = ofpbuf_at_assert(reply, start_ofs, sizeof *ofs);
2159         ofs->length = htons(reply->size - start_ofs);
2160         ofs->table_id = fs->table_id;
2161         ofs->pad = 0;
2162         ofs->duration_sec = htonl(fs->duration_sec);
2163         ofs->duration_nsec = htonl(fs->duration_nsec);
2164         ofs->priority = htons(fs->priority);
2165         ofs->idle_timeout = htons(fs->idle_timeout);
2166         ofs->hard_timeout = htons(fs->hard_timeout);
2167         ofs->flags = (raw == OFPRAW_OFPST13_FLOW_REPLY) ? htons(fs->flags) : 0;
2168         memset(ofs->pad2, 0, sizeof ofs->pad2);
2169         ofs->cookie = fs->cookie;
2170         ofs->packet_count = htonll(unknown_to_zero(fs->packet_count));
2171         ofs->byte_count = htonll(unknown_to_zero(fs->byte_count));
2172     } else if (raw == OFPRAW_OFPST10_FLOW_REPLY) {
2173         struct ofp10_flow_stats *ofs;
2174
2175         ofpbuf_put_uninit(reply, sizeof *ofs);
2176         ofpacts_put_openflow10(fs->ofpacts, fs->ofpacts_len, reply);
2177
2178         ofs = ofpbuf_at_assert(reply, start_ofs, sizeof *ofs);
2179         ofs->length = htons(reply->size - start_ofs);
2180         ofs->table_id = fs->table_id;
2181         ofs->pad = 0;
2182         ofputil_match_to_ofp10_match(&fs->match, &ofs->match);
2183         ofs->duration_sec = htonl(fs->duration_sec);
2184         ofs->duration_nsec = htonl(fs->duration_nsec);
2185         ofs->priority = htons(fs->priority);
2186         ofs->idle_timeout = htons(fs->idle_timeout);
2187         ofs->hard_timeout = htons(fs->hard_timeout);
2188         memset(ofs->pad2, 0, sizeof ofs->pad2);
2189         put_32aligned_be64(&ofs->cookie, fs->cookie);
2190         put_32aligned_be64(&ofs->packet_count,
2191                            htonll(unknown_to_zero(fs->packet_count)));
2192         put_32aligned_be64(&ofs->byte_count,
2193                            htonll(unknown_to_zero(fs->byte_count)));
2194     } else if (raw == OFPRAW_NXST_FLOW_REPLY) {
2195         struct nx_flow_stats *nfs;
2196         int match_len;
2197
2198         ofpbuf_put_uninit(reply, sizeof *nfs);
2199         match_len = nx_put_match(reply, &fs->match, 0, 0);
2200         ofpacts_put_openflow10(fs->ofpacts, fs->ofpacts_len, reply);
2201
2202         nfs = ofpbuf_at_assert(reply, start_ofs, sizeof *nfs);
2203         nfs->length = htons(reply->size - start_ofs);
2204         nfs->table_id = fs->table_id;
2205         nfs->pad = 0;
2206         nfs->duration_sec = htonl(fs->duration_sec);
2207         nfs->duration_nsec = htonl(fs->duration_nsec);
2208         nfs->priority = htons(fs->priority);
2209         nfs->idle_timeout = htons(fs->idle_timeout);
2210         nfs->hard_timeout = htons(fs->hard_timeout);
2211         nfs->idle_age = htons(fs->idle_age < 0 ? 0
2212                               : fs->idle_age < UINT16_MAX ? fs->idle_age + 1
2213                               : UINT16_MAX);
2214         nfs->hard_age = htons(fs->hard_age < 0 ? 0
2215                               : fs->hard_age < UINT16_MAX ? fs->hard_age + 1
2216                               : UINT16_MAX);
2217         nfs->match_len = htons(match_len);
2218         nfs->cookie = fs->cookie;
2219         nfs->packet_count = htonll(fs->packet_count);
2220         nfs->byte_count = htonll(fs->byte_count);
2221     } else {
2222         NOT_REACHED();
2223     }
2224
2225     ofpmp_postappend(replies, start_ofs);
2226 }
2227
2228 /* Converts abstract ofputil_aggregate_stats 'stats' into an OFPST_AGGREGATE or
2229  * NXST_AGGREGATE reply matching 'request', and returns the message. */
2230 struct ofpbuf *
2231 ofputil_encode_aggregate_stats_reply(
2232     const struct ofputil_aggregate_stats *stats,
2233     const struct ofp_header *request)
2234 {
2235     struct ofp_aggregate_stats_reply *asr;
2236     uint64_t packet_count;
2237     uint64_t byte_count;
2238     struct ofpbuf *msg;
2239     enum ofpraw raw;
2240
2241     ofpraw_decode(&raw, request);
2242     if (raw == OFPRAW_OFPST10_AGGREGATE_REQUEST) {
2243         packet_count = unknown_to_zero(stats->packet_count);
2244         byte_count = unknown_to_zero(stats->byte_count);
2245     } else {
2246         packet_count = stats->packet_count;
2247         byte_count = stats->byte_count;
2248     }
2249
2250     msg = ofpraw_alloc_stats_reply(request, 0);
2251     asr = ofpbuf_put_zeros(msg, sizeof *asr);
2252     put_32aligned_be64(&asr->packet_count, htonll(packet_count));
2253     put_32aligned_be64(&asr->byte_count, htonll(byte_count));
2254     asr->flow_count = htonl(stats->flow_count);
2255
2256     return msg;
2257 }
2258
2259 enum ofperr
2260 ofputil_decode_aggregate_stats_reply(struct ofputil_aggregate_stats *stats,
2261                                      const struct ofp_header *reply)
2262 {
2263     struct ofp_aggregate_stats_reply *asr;
2264     struct ofpbuf msg;
2265
2266     ofpbuf_use_const(&msg, reply, ntohs(reply->length));
2267     ofpraw_pull_assert(&msg);
2268
2269     asr = msg.l3;
2270     stats->packet_count = ntohll(get_32aligned_be64(&asr->packet_count));
2271     stats->byte_count = ntohll(get_32aligned_be64(&asr->byte_count));
2272     stats->flow_count = ntohl(asr->flow_count);
2273
2274     return 0;
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     enum ofpraw raw;
2285     struct ofpbuf b;
2286
2287     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2288     raw = ofpraw_pull_assert(&b);
2289     if (raw == OFPRAW_OFPT11_FLOW_REMOVED) {
2290         const struct ofp12_flow_removed *ofr;
2291         enum ofperr error;
2292
2293         ofr = ofpbuf_pull(&b, sizeof *ofr);
2294
2295         error = ofputil_pull_ofp11_match(&b, &fr->match, NULL);
2296         if (error) {
2297             return error;
2298         }
2299
2300         fr->priority = ntohs(ofr->priority);
2301         fr->cookie = ofr->cookie;
2302         fr->reason = ofr->reason;
2303         fr->table_id = ofr->table_id;
2304         fr->duration_sec = ntohl(ofr->duration_sec);
2305         fr->duration_nsec = ntohl(ofr->duration_nsec);
2306         fr->idle_timeout = ntohs(ofr->idle_timeout);
2307         fr->hard_timeout = ntohs(ofr->hard_timeout);
2308         fr->packet_count = ntohll(ofr->packet_count);
2309         fr->byte_count = ntohll(ofr->byte_count);
2310     } else if (raw == OFPRAW_OFPT10_FLOW_REMOVED) {
2311         const struct ofp10_flow_removed *ofr;
2312
2313         ofr = ofpbuf_pull(&b, sizeof *ofr);
2314
2315         ofputil_match_from_ofp10_match(&ofr->match, &fr->match);
2316         fr->priority = ntohs(ofr->priority);
2317         fr->cookie = ofr->cookie;
2318         fr->reason = ofr->reason;
2319         fr->table_id = 255;
2320         fr->duration_sec = ntohl(ofr->duration_sec);
2321         fr->duration_nsec = ntohl(ofr->duration_nsec);
2322         fr->idle_timeout = ntohs(ofr->idle_timeout);
2323         fr->hard_timeout = 0;
2324         fr->packet_count = ntohll(ofr->packet_count);
2325         fr->byte_count = ntohll(ofr->byte_count);
2326     } else if (raw == OFPRAW_NXT_FLOW_REMOVED) {
2327         struct nx_flow_removed *nfr;
2328         enum ofperr error;
2329
2330         nfr = ofpbuf_pull(&b, sizeof *nfr);
2331         error = nx_pull_match(&b, ntohs(nfr->match_len), &fr->match,
2332                               NULL, NULL);
2333         if (error) {
2334             return error;
2335         }
2336         if (b.size) {
2337             return OFPERR_OFPBRC_BAD_LEN;
2338         }
2339
2340         fr->priority = ntohs(nfr->priority);
2341         fr->cookie = nfr->cookie;
2342         fr->reason = nfr->reason;
2343         fr->table_id = nfr->table_id ? nfr->table_id - 1 : 255;
2344         fr->duration_sec = ntohl(nfr->duration_sec);
2345         fr->duration_nsec = ntohl(nfr->duration_nsec);
2346         fr->idle_timeout = ntohs(nfr->idle_timeout);
2347         fr->hard_timeout = 0;
2348         fr->packet_count = ntohll(nfr->packet_count);
2349         fr->byte_count = ntohll(nfr->byte_count);
2350     } else {
2351         NOT_REACHED();
2352     }
2353
2354     return 0;
2355 }
2356
2357 /* Converts abstract ofputil_flow_removed 'fr' into an OFPT_FLOW_REMOVED or
2358  * NXT_FLOW_REMOVED message 'oh' according to 'protocol', and returns the
2359  * message. */
2360 struct ofpbuf *
2361 ofputil_encode_flow_removed(const struct ofputil_flow_removed *fr,
2362                             enum ofputil_protocol protocol)
2363 {
2364     struct ofpbuf *msg;
2365
2366     switch (protocol) {
2367     case OFPUTIL_P_OF12_OXM:
2368     case OFPUTIL_P_OF13_OXM: {
2369         struct ofp12_flow_removed *ofr;
2370
2371         msg = ofpraw_alloc_xid(OFPRAW_OFPT11_FLOW_REMOVED,
2372                                ofputil_protocol_to_ofp_version(protocol),
2373                                htonl(0), NXM_TYPICAL_LEN);
2374         ofr = ofpbuf_put_zeros(msg, sizeof *ofr);
2375         ofr->cookie = fr->cookie;
2376         ofr->priority = htons(fr->priority);
2377         ofr->reason = fr->reason;
2378         ofr->table_id = fr->table_id;
2379         ofr->duration_sec = htonl(fr->duration_sec);
2380         ofr->duration_nsec = htonl(fr->duration_nsec);
2381         ofr->idle_timeout = htons(fr->idle_timeout);
2382         ofr->hard_timeout = htons(fr->hard_timeout);
2383         ofr->packet_count = htonll(fr->packet_count);
2384         ofr->byte_count = htonll(fr->byte_count);
2385         oxm_put_match(msg, &fr->match);
2386         break;
2387     }
2388
2389     case OFPUTIL_P_OF10_STD:
2390     case OFPUTIL_P_OF10_STD_TID: {
2391         struct ofp10_flow_removed *ofr;
2392
2393         msg = ofpraw_alloc_xid(OFPRAW_OFPT10_FLOW_REMOVED, OFP10_VERSION,
2394                                htonl(0), 0);
2395         ofr = ofpbuf_put_zeros(msg, sizeof *ofr);
2396         ofputil_match_to_ofp10_match(&fr->match, &ofr->match);
2397         ofr->cookie = fr->cookie;
2398         ofr->priority = htons(fr->priority);
2399         ofr->reason = fr->reason;
2400         ofr->duration_sec = htonl(fr->duration_sec);
2401         ofr->duration_nsec = htonl(fr->duration_nsec);
2402         ofr->idle_timeout = htons(fr->idle_timeout);
2403         ofr->packet_count = htonll(unknown_to_zero(fr->packet_count));
2404         ofr->byte_count = htonll(unknown_to_zero(fr->byte_count));
2405         break;
2406     }
2407
2408     case OFPUTIL_P_OF10_NXM:
2409     case OFPUTIL_P_OF10_NXM_TID: {
2410         struct nx_flow_removed *nfr;
2411         int match_len;
2412
2413         msg = ofpraw_alloc_xid(OFPRAW_NXT_FLOW_REMOVED, OFP10_VERSION,
2414                                htonl(0), NXM_TYPICAL_LEN);
2415         nfr = ofpbuf_put_zeros(msg, sizeof *nfr);
2416         match_len = nx_put_match(msg, &fr->match, 0, 0);
2417
2418         nfr = msg->l3;
2419         nfr->cookie = fr->cookie;
2420         nfr->priority = htons(fr->priority);
2421         nfr->reason = fr->reason;
2422         nfr->table_id = fr->table_id + 1;
2423         nfr->duration_sec = htonl(fr->duration_sec);
2424         nfr->duration_nsec = htonl(fr->duration_nsec);
2425         nfr->idle_timeout = htons(fr->idle_timeout);
2426         nfr->match_len = htons(match_len);
2427         nfr->packet_count = htonll(fr->packet_count);
2428         nfr->byte_count = htonll(fr->byte_count);
2429         break;
2430     }
2431
2432     default:
2433         NOT_REACHED();
2434     }
2435
2436     return msg;
2437 }
2438
2439 static void
2440 ofputil_decode_packet_in_finish(struct ofputil_packet_in *pin,
2441                                 struct match *match, struct ofpbuf *b)
2442 {
2443     pin->packet = b->data;
2444     pin->packet_len = b->size;
2445
2446     pin->fmd.in_port = match->flow.in_port;
2447     pin->fmd.tun_id = match->flow.tunnel.tun_id;
2448     pin->fmd.tun_src = match->flow.tunnel.ip_src;
2449     pin->fmd.tun_dst = match->flow.tunnel.ip_dst;
2450     pin->fmd.metadata = match->flow.metadata;
2451     memcpy(pin->fmd.regs, match->flow.regs, sizeof pin->fmd.regs);
2452 }
2453
2454 enum ofperr
2455 ofputil_decode_packet_in(struct ofputil_packet_in *pin,
2456                          const struct ofp_header *oh)
2457 {
2458     enum ofpraw raw;
2459     struct ofpbuf b;
2460
2461     memset(pin, 0, sizeof *pin);
2462
2463     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2464     raw = ofpraw_pull_assert(&b);
2465     if (raw == OFPRAW_OFPT13_PACKET_IN || raw == OFPRAW_OFPT12_PACKET_IN) {
2466         const struct ofp13_packet_in *opi;
2467         struct match match;
2468         int error;
2469         size_t packet_in_size;
2470
2471         if (raw == OFPRAW_OFPT12_PACKET_IN) {
2472             packet_in_size = sizeof (struct ofp12_packet_in);
2473         } else {
2474             packet_in_size = sizeof (struct ofp13_packet_in);
2475         }
2476
2477         opi = ofpbuf_pull(&b, packet_in_size);
2478         error = oxm_pull_match_loose(&b, &match);
2479         if (error) {
2480             return error;
2481         }
2482
2483         if (!ofpbuf_try_pull(&b, 2)) {
2484             return OFPERR_OFPBRC_BAD_LEN;
2485         }
2486
2487         pin->reason = opi->pi.reason;
2488         pin->table_id = opi->pi.table_id;
2489         pin->buffer_id = ntohl(opi->pi.buffer_id);
2490         pin->total_len = ntohs(opi->pi.total_len);
2491
2492         if (raw == OFPRAW_OFPT13_PACKET_IN) {
2493             pin->cookie = opi->cookie;
2494         }
2495
2496         ofputil_decode_packet_in_finish(pin, &match, &b);
2497     } else if (raw == OFPRAW_OFPT10_PACKET_IN) {
2498         const struct ofp10_packet_in *opi;
2499
2500         opi = ofpbuf_pull(&b, offsetof(struct ofp10_packet_in, data));
2501
2502         pin->packet = opi->data;
2503         pin->packet_len = b.size;
2504
2505         pin->fmd.in_port = ntohs(opi->in_port);
2506         pin->reason = opi->reason;
2507         pin->buffer_id = ntohl(opi->buffer_id);
2508         pin->total_len = ntohs(opi->total_len);
2509     } else if (raw == OFPRAW_NXT_PACKET_IN) {
2510         const struct nx_packet_in *npi;
2511         struct match match;
2512         int error;
2513
2514         npi = ofpbuf_pull(&b, sizeof *npi);
2515         error = nx_pull_match_loose(&b, ntohs(npi->match_len), &match, NULL,
2516                                     NULL);
2517         if (error) {
2518             return error;
2519         }
2520
2521         if (!ofpbuf_try_pull(&b, 2)) {
2522             return OFPERR_OFPBRC_BAD_LEN;
2523         }
2524
2525         pin->reason = npi->reason;
2526         pin->table_id = npi->table_id;
2527         pin->cookie = npi->cookie;
2528
2529         pin->buffer_id = ntohl(npi->buffer_id);
2530         pin->total_len = ntohs(npi->total_len);
2531
2532         ofputil_decode_packet_in_finish(pin, &match, &b);
2533     } else {
2534         NOT_REACHED();
2535     }
2536
2537     return 0;
2538 }
2539
2540 static void
2541 ofputil_packet_in_to_match(const struct ofputil_packet_in *pin,
2542                            struct match *match)
2543 {
2544     int i;
2545
2546     match_init_catchall(match);
2547     if (pin->fmd.tun_id != htonll(0)) {
2548         match_set_tun_id(match, pin->fmd.tun_id);
2549     }
2550     if (pin->fmd.tun_src != htonl(0)) {
2551         match_set_tun_src(match, pin->fmd.tun_src);
2552     }
2553     if (pin->fmd.tun_dst != htonl(0)) {
2554         match_set_tun_dst(match, pin->fmd.tun_dst);
2555     }
2556     if (pin->fmd.metadata != htonll(0)) {
2557         match_set_metadata(match, pin->fmd.metadata);
2558     }
2559
2560     for (i = 0; i < FLOW_N_REGS; i++) {
2561         if (pin->fmd.regs[i]) {
2562             match_set_reg(match, i, pin->fmd.regs[i]);
2563         }
2564     }
2565
2566     match_set_in_port(match, pin->fmd.in_port);
2567 }
2568
2569 /* Converts abstract ofputil_packet_in 'pin' into a PACKET_IN message
2570  * in the format specified by 'packet_in_format'.  */
2571 struct ofpbuf *
2572 ofputil_encode_packet_in(const struct ofputil_packet_in *pin,
2573                          enum ofputil_protocol protocol,
2574                          enum nx_packet_in_format packet_in_format)
2575 {
2576     size_t send_len = MIN(pin->send_len, pin->packet_len);
2577     struct ofpbuf *packet;
2578
2579     /* Add OFPT_PACKET_IN. */
2580     if (protocol == OFPUTIL_P_OF13_OXM || protocol == OFPUTIL_P_OF12_OXM) {
2581         struct ofp13_packet_in *opi;
2582         struct match match;
2583         enum ofpraw packet_in_raw;
2584         enum ofp_version packet_in_version;
2585         size_t packet_in_size;
2586
2587         if (protocol == OFPUTIL_P_OF12_OXM) {
2588             packet_in_raw = OFPRAW_OFPT12_PACKET_IN;
2589             packet_in_version = OFP12_VERSION;
2590             packet_in_size = sizeof (struct ofp12_packet_in);
2591         } else {
2592             packet_in_raw = OFPRAW_OFPT13_PACKET_IN;
2593             packet_in_version = OFP13_VERSION;
2594             packet_in_size = sizeof (struct ofp13_packet_in);
2595         }
2596
2597         ofputil_packet_in_to_match(pin, &match);
2598
2599         /* The final argument is just an estimate of the space required. */
2600         packet = ofpraw_alloc_xid(packet_in_raw, packet_in_version,
2601                                   htonl(0), (sizeof(struct flow_metadata) * 2
2602                                              + 2 + send_len));
2603         ofpbuf_put_zeros(packet, packet_in_size);
2604         oxm_put_match(packet, &match);
2605         ofpbuf_put_zeros(packet, 2);
2606         ofpbuf_put(packet, pin->packet, send_len);
2607
2608         opi = packet->l3;
2609         opi->pi.buffer_id = htonl(pin->buffer_id);
2610         opi->pi.total_len = htons(pin->total_len);
2611         opi->pi.reason = pin->reason;
2612         opi->pi.table_id = pin->table_id;
2613         if (protocol == OFPUTIL_P_OF13_OXM) {
2614             opi->cookie = pin->cookie;
2615         }
2616     } else if (packet_in_format == NXPIF_OPENFLOW10) {
2617         struct ofp10_packet_in *opi;
2618
2619         packet = ofpraw_alloc_xid(OFPRAW_OFPT10_PACKET_IN, OFP10_VERSION,
2620                                   htonl(0), send_len);
2621         opi = ofpbuf_put_zeros(packet, offsetof(struct ofp10_packet_in, data));
2622         opi->total_len = htons(pin->total_len);
2623         opi->in_port = htons(pin->fmd.in_port);
2624         opi->reason = pin->reason;
2625         opi->buffer_id = htonl(pin->buffer_id);
2626
2627         ofpbuf_put(packet, pin->packet, send_len);
2628     } else if (packet_in_format == NXPIF_NXM) {
2629         struct nx_packet_in *npi;
2630         struct match match;
2631         size_t match_len;
2632
2633         ofputil_packet_in_to_match(pin, &match);
2634
2635         /* The final argument is just an estimate of the space required. */
2636         packet = ofpraw_alloc_xid(OFPRAW_NXT_PACKET_IN, OFP10_VERSION,
2637                                   htonl(0), (sizeof(struct flow_metadata) * 2
2638                                              + 2 + send_len));
2639         ofpbuf_put_zeros(packet, sizeof *npi);
2640         match_len = nx_put_match(packet, &match, 0, 0);
2641         ofpbuf_put_zeros(packet, 2);
2642         ofpbuf_put(packet, pin->packet, send_len);
2643
2644         npi = packet->l3;
2645         npi->buffer_id = htonl(pin->buffer_id);
2646         npi->total_len = htons(pin->total_len);
2647         npi->reason = pin->reason;
2648         npi->table_id = pin->table_id;
2649         npi->cookie = pin->cookie;
2650         npi->match_len = htons(match_len);
2651     } else {
2652         NOT_REACHED();
2653     }
2654     ofpmsg_update_length(packet);
2655
2656     return packet;
2657 }
2658
2659 /* Returns a string form of 'reason'.  The return value is either a statically
2660  * allocated constant string or the 'bufsize'-byte buffer 'reasonbuf'.
2661  * 'bufsize' should be at least OFPUTIL_PACKET_IN_REASON_BUFSIZE. */
2662 const char *
2663 ofputil_packet_in_reason_to_string(enum ofp_packet_in_reason reason,
2664                                    char *reasonbuf, size_t bufsize)
2665 {
2666     switch (reason) {
2667     case OFPR_NO_MATCH:
2668         return "no_match";
2669     case OFPR_ACTION:
2670         return "action";
2671     case OFPR_INVALID_TTL:
2672         return "invalid_ttl";
2673
2674     case OFPR_N_REASONS:
2675     default:
2676         snprintf(reasonbuf, bufsize, "%d", (int) reason);
2677         return reasonbuf;
2678     }
2679 }
2680
2681 bool
2682 ofputil_packet_in_reason_from_string(const char *s,
2683                                      enum ofp_packet_in_reason *reason)
2684 {
2685     int i;
2686
2687     for (i = 0; i < OFPR_N_REASONS; i++) {
2688         char reasonbuf[OFPUTIL_PACKET_IN_REASON_BUFSIZE];
2689         const char *reason_s;
2690
2691         reason_s = ofputil_packet_in_reason_to_string(i, reasonbuf,
2692                                                       sizeof reasonbuf);
2693         if (!strcasecmp(s, reason_s)) {
2694             *reason = i;
2695             return true;
2696         }
2697     }
2698     return false;
2699 }
2700
2701 /* Converts an OFPT_PACKET_OUT in 'opo' into an abstract ofputil_packet_out in
2702  * 'po'.
2703  *
2704  * Uses 'ofpacts' to store the abstract OFPACT_* version of the packet out
2705  * message's actions.  The caller must initialize 'ofpacts' and retains
2706  * ownership of it.  'po->ofpacts' will point into the 'ofpacts' buffer.
2707  *
2708  * Returns 0 if successful, otherwise an OFPERR_* value. */
2709 enum ofperr
2710 ofputil_decode_packet_out(struct ofputil_packet_out *po,
2711                           const struct ofp_header *oh,
2712                           struct ofpbuf *ofpacts)
2713 {
2714     enum ofpraw raw;
2715     struct ofpbuf b;
2716
2717     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2718     raw = ofpraw_pull_assert(&b);
2719
2720     if (raw == OFPRAW_OFPT11_PACKET_OUT) {
2721         enum ofperr error;
2722         const struct ofp11_packet_out *opo = ofpbuf_pull(&b, sizeof *opo);
2723
2724         po->buffer_id = ntohl(opo->buffer_id);
2725         error = ofputil_port_from_ofp11(opo->in_port, &po->in_port);
2726         if (error) {
2727             return error;
2728         }
2729
2730         error = ofpacts_pull_openflow11_actions(&b, ntohs(opo->actions_len),
2731                                                 ofpacts);
2732         if (error) {
2733             return error;
2734         }
2735     } else if (raw == OFPRAW_OFPT10_PACKET_OUT) {
2736         enum ofperr error;
2737         const struct ofp10_packet_out *opo = ofpbuf_pull(&b, sizeof *opo);
2738
2739         po->buffer_id = ntohl(opo->buffer_id);
2740         po->in_port = ntohs(opo->in_port);
2741
2742         error = ofpacts_pull_openflow10(&b, ntohs(opo->actions_len), ofpacts);
2743         if (error) {
2744             return error;
2745         }
2746     } else {
2747         NOT_REACHED();
2748     }
2749
2750     if (po->in_port >= OFPP_MAX && po->in_port != OFPP_LOCAL
2751         && po->in_port != OFPP_NONE && po->in_port != OFPP_CONTROLLER) {
2752         VLOG_WARN_RL(&bad_ofmsg_rl, "packet-out has bad input port %#"PRIx16,
2753                      po->in_port);
2754         return OFPERR_OFPBRC_BAD_PORT;
2755     }
2756
2757     po->ofpacts = ofpacts->data;
2758     po->ofpacts_len = ofpacts->size;
2759
2760     if (po->buffer_id == UINT32_MAX) {
2761         po->packet = b.data;
2762         po->packet_len = b.size;
2763     } else {
2764         po->packet = NULL;
2765         po->packet_len = 0;
2766     }
2767
2768     return 0;
2769 }
2770 \f
2771 /* ofputil_phy_port */
2772
2773 /* NETDEV_F_* to and from OFPPF_* and OFPPF10_*. */
2774 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_HD    == OFPPF_10MB_HD);  /* bit 0 */
2775 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_FD    == OFPPF_10MB_FD);  /* bit 1 */
2776 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_HD   == OFPPF_100MB_HD); /* bit 2 */
2777 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_FD   == OFPPF_100MB_FD); /* bit 3 */
2778 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_HD     == OFPPF_1GB_HD);   /* bit 4 */
2779 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_FD     == OFPPF_1GB_FD);   /* bit 5 */
2780 BUILD_ASSERT_DECL((int) NETDEV_F_10GB_FD    == OFPPF_10GB_FD);  /* bit 6 */
2781
2782 /* NETDEV_F_ bits 11...15 are OFPPF10_ bits 7...11: */
2783 BUILD_ASSERT_DECL((int) NETDEV_F_COPPER == (OFPPF10_COPPER << 4));
2784 BUILD_ASSERT_DECL((int) NETDEV_F_FIBER == (OFPPF10_FIBER << 4));
2785 BUILD_ASSERT_DECL((int) NETDEV_F_AUTONEG == (OFPPF10_AUTONEG << 4));
2786 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE == (OFPPF10_PAUSE << 4));
2787 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE_ASYM == (OFPPF10_PAUSE_ASYM << 4));
2788
2789 static enum netdev_features
2790 netdev_port_features_from_ofp10(ovs_be32 ofp10_)
2791 {
2792     uint32_t ofp10 = ntohl(ofp10_);
2793     return (ofp10 & 0x7f) | ((ofp10 & 0xf80) << 4);
2794 }
2795
2796 static ovs_be32
2797 netdev_port_features_to_ofp10(enum netdev_features features)
2798 {
2799     return htonl((features & 0x7f) | ((features & 0xf800) >> 4));
2800 }
2801
2802 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_HD    == OFPPF_10MB_HD);     /* bit 0 */
2803 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_FD    == OFPPF_10MB_FD);     /* bit 1 */
2804 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_HD   == OFPPF_100MB_HD);    /* bit 2 */
2805 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_FD   == OFPPF_100MB_FD);    /* bit 3 */
2806 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_HD     == OFPPF_1GB_HD);      /* bit 4 */
2807 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_FD     == OFPPF_1GB_FD);      /* bit 5 */
2808 BUILD_ASSERT_DECL((int) NETDEV_F_10GB_FD    == OFPPF_10GB_FD);     /* bit 6 */
2809 BUILD_ASSERT_DECL((int) NETDEV_F_40GB_FD    == OFPPF11_40GB_FD);   /* bit 7 */
2810 BUILD_ASSERT_DECL((int) NETDEV_F_100GB_FD   == OFPPF11_100GB_FD);  /* bit 8 */
2811 BUILD_ASSERT_DECL((int) NETDEV_F_1TB_FD     == OFPPF11_1TB_FD);    /* bit 9 */
2812 BUILD_ASSERT_DECL((int) NETDEV_F_OTHER      == OFPPF11_OTHER);     /* bit 10 */
2813 BUILD_ASSERT_DECL((int) NETDEV_F_COPPER     == OFPPF11_COPPER);    /* bit 11 */
2814 BUILD_ASSERT_DECL((int) NETDEV_F_FIBER      == OFPPF11_FIBER);     /* bit 12 */
2815 BUILD_ASSERT_DECL((int) NETDEV_F_AUTONEG    == OFPPF11_AUTONEG);   /* bit 13 */
2816 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE      == OFPPF11_PAUSE);     /* bit 14 */
2817 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE_ASYM == OFPPF11_PAUSE_ASYM);/* bit 15 */
2818
2819 static enum netdev_features
2820 netdev_port_features_from_ofp11(ovs_be32 ofp11)
2821 {
2822     return ntohl(ofp11) & 0xffff;
2823 }
2824
2825 static ovs_be32
2826 netdev_port_features_to_ofp11(enum netdev_features features)
2827 {
2828     return htonl(features & 0xffff);
2829 }
2830
2831 static enum ofperr
2832 ofputil_decode_ofp10_phy_port(struct ofputil_phy_port *pp,
2833                               const struct ofp10_phy_port *opp)
2834 {
2835     memset(pp, 0, sizeof *pp);
2836
2837     pp->port_no = ntohs(opp->port_no);
2838     memcpy(pp->hw_addr, opp->hw_addr, OFP_ETH_ALEN);
2839     ovs_strlcpy(pp->name, opp->name, OFP_MAX_PORT_NAME_LEN);
2840
2841     pp->config = ntohl(opp->config) & OFPPC10_ALL;
2842     pp->state = ntohl(opp->state) & OFPPS10_ALL;
2843
2844     pp->curr = netdev_port_features_from_ofp10(opp->curr);
2845     pp->advertised = netdev_port_features_from_ofp10(opp->advertised);
2846     pp->supported = netdev_port_features_from_ofp10(opp->supported);
2847     pp->peer = netdev_port_features_from_ofp10(opp->peer);
2848
2849     pp->curr_speed = netdev_features_to_bps(pp->curr, 0) / 1000;
2850     pp->max_speed = netdev_features_to_bps(pp->supported, 0) / 1000;
2851
2852     return 0;
2853 }
2854
2855 static enum ofperr
2856 ofputil_decode_ofp11_port(struct ofputil_phy_port *pp,
2857                           const struct ofp11_port *op)
2858 {
2859     enum ofperr error;
2860
2861     memset(pp, 0, sizeof *pp);
2862
2863     error = ofputil_port_from_ofp11(op->port_no, &pp->port_no);
2864     if (error) {
2865         return error;
2866     }
2867     memcpy(pp->hw_addr, op->hw_addr, OFP_ETH_ALEN);
2868     ovs_strlcpy(pp->name, op->name, OFP_MAX_PORT_NAME_LEN);
2869
2870     pp->config = ntohl(op->config) & OFPPC11_ALL;
2871     pp->state = ntohl(op->state) & OFPPC11_ALL;
2872
2873     pp->curr = netdev_port_features_from_ofp11(op->curr);
2874     pp->advertised = netdev_port_features_from_ofp11(op->advertised);
2875     pp->supported = netdev_port_features_from_ofp11(op->supported);
2876     pp->peer = netdev_port_features_from_ofp11(op->peer);
2877
2878     pp->curr_speed = ntohl(op->curr_speed);
2879     pp->max_speed = ntohl(op->max_speed);
2880
2881     return 0;
2882 }
2883
2884 static size_t
2885 ofputil_get_phy_port_size(enum ofp_version ofp_version)
2886 {
2887     switch (ofp_version) {
2888     case OFP10_VERSION:
2889         return sizeof(struct ofp10_phy_port);
2890     case OFP11_VERSION:
2891     case OFP12_VERSION:
2892     case OFP13_VERSION:
2893         return sizeof(struct ofp11_port);
2894     default:
2895         NOT_REACHED();
2896     }
2897 }
2898
2899 static void
2900 ofputil_encode_ofp10_phy_port(const struct ofputil_phy_port *pp,
2901                               struct ofp10_phy_port *opp)
2902 {
2903     memset(opp, 0, sizeof *opp);
2904
2905     opp->port_no = htons(pp->port_no);
2906     memcpy(opp->hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2907     ovs_strlcpy(opp->name, pp->name, OFP_MAX_PORT_NAME_LEN);
2908
2909     opp->config = htonl(pp->config & OFPPC10_ALL);
2910     opp->state = htonl(pp->state & OFPPS10_ALL);
2911
2912     opp->curr = netdev_port_features_to_ofp10(pp->curr);
2913     opp->advertised = netdev_port_features_to_ofp10(pp->advertised);
2914     opp->supported = netdev_port_features_to_ofp10(pp->supported);
2915     opp->peer = netdev_port_features_to_ofp10(pp->peer);
2916 }
2917
2918 static void
2919 ofputil_encode_ofp11_port(const struct ofputil_phy_port *pp,
2920                           struct ofp11_port *op)
2921 {
2922     memset(op, 0, sizeof *op);
2923
2924     op->port_no = ofputil_port_to_ofp11(pp->port_no);
2925     memcpy(op->hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2926     ovs_strlcpy(op->name, pp->name, OFP_MAX_PORT_NAME_LEN);
2927
2928     op->config = htonl(pp->config & OFPPC11_ALL);
2929     op->state = htonl(pp->state & OFPPS11_ALL);
2930
2931     op->curr = netdev_port_features_to_ofp11(pp->curr);
2932     op->advertised = netdev_port_features_to_ofp11(pp->advertised);
2933     op->supported = netdev_port_features_to_ofp11(pp->supported);
2934     op->peer = netdev_port_features_to_ofp11(pp->peer);
2935
2936     op->curr_speed = htonl(pp->curr_speed);
2937     op->max_speed = htonl(pp->max_speed);
2938 }
2939
2940 static void
2941 ofputil_put_phy_port(enum ofp_version ofp_version,
2942                      const struct ofputil_phy_port *pp, struct ofpbuf *b)
2943 {
2944     switch (ofp_version) {
2945     case OFP10_VERSION: {
2946         struct ofp10_phy_port *opp;
2947         if (b->size + sizeof *opp <= UINT16_MAX) {
2948             opp = ofpbuf_put_uninit(b, sizeof *opp);
2949             ofputil_encode_ofp10_phy_port(pp, opp);
2950         }
2951         break;
2952     }
2953
2954     case OFP11_VERSION:
2955     case OFP12_VERSION:
2956     case OFP13_VERSION: {
2957         struct ofp11_port *op;
2958         if (b->size + sizeof *op <= UINT16_MAX) {
2959             op = ofpbuf_put_uninit(b, sizeof *op);
2960             ofputil_encode_ofp11_port(pp, op);
2961         }
2962         break;
2963     }
2964
2965     default:
2966         NOT_REACHED();
2967     }
2968 }
2969
2970 void
2971 ofputil_append_port_desc_stats_reply(enum ofp_version ofp_version,
2972                                      const struct ofputil_phy_port *pp,
2973                                      struct list *replies)
2974 {
2975     switch (ofp_version) {
2976     case OFP10_VERSION: {
2977         struct ofp10_phy_port *opp;
2978
2979         opp = ofpmp_append(replies, sizeof *opp);
2980         ofputil_encode_ofp10_phy_port(pp, opp);
2981         break;
2982     }
2983
2984     case OFP11_VERSION:
2985     case OFP12_VERSION:
2986     case OFP13_VERSION: {
2987         struct ofp11_port *op;
2988
2989         op = ofpmp_append(replies, sizeof *op);
2990         ofputil_encode_ofp11_port(pp, op);
2991         break;
2992     }
2993
2994     default:
2995       NOT_REACHED();
2996     }
2997 }
2998 \f
2999 /* ofputil_switch_features */
3000
3001 #define OFPC_COMMON (OFPC_FLOW_STATS | OFPC_TABLE_STATS | OFPC_PORT_STATS | \
3002                      OFPC_IP_REASM | OFPC_QUEUE_STATS)
3003 BUILD_ASSERT_DECL((int) OFPUTIL_C_FLOW_STATS == OFPC_FLOW_STATS);
3004 BUILD_ASSERT_DECL((int) OFPUTIL_C_TABLE_STATS == OFPC_TABLE_STATS);
3005 BUILD_ASSERT_DECL((int) OFPUTIL_C_PORT_STATS == OFPC_PORT_STATS);
3006 BUILD_ASSERT_DECL((int) OFPUTIL_C_IP_REASM == OFPC_IP_REASM);
3007 BUILD_ASSERT_DECL((int) OFPUTIL_C_QUEUE_STATS == OFPC_QUEUE_STATS);
3008 BUILD_ASSERT_DECL((int) OFPUTIL_C_ARP_MATCH_IP == OFPC_ARP_MATCH_IP);
3009
3010 struct ofputil_action_bit_translation {
3011     enum ofputil_action_bitmap ofputil_bit;
3012     int of_bit;
3013 };
3014
3015 static const struct ofputil_action_bit_translation of10_action_bits[] = {
3016     { OFPUTIL_A_OUTPUT,       OFPAT10_OUTPUT },
3017     { OFPUTIL_A_SET_VLAN_VID, OFPAT10_SET_VLAN_VID },
3018     { OFPUTIL_A_SET_VLAN_PCP, OFPAT10_SET_VLAN_PCP },
3019     { OFPUTIL_A_STRIP_VLAN,   OFPAT10_STRIP_VLAN },
3020     { OFPUTIL_A_SET_DL_SRC,   OFPAT10_SET_DL_SRC },
3021     { OFPUTIL_A_SET_DL_DST,   OFPAT10_SET_DL_DST },
3022     { OFPUTIL_A_SET_NW_SRC,   OFPAT10_SET_NW_SRC },
3023     { OFPUTIL_A_SET_NW_DST,   OFPAT10_SET_NW_DST },
3024     { OFPUTIL_A_SET_NW_TOS,   OFPAT10_SET_NW_TOS },
3025     { OFPUTIL_A_SET_TP_SRC,   OFPAT10_SET_TP_SRC },
3026     { OFPUTIL_A_SET_TP_DST,   OFPAT10_SET_TP_DST },
3027     { OFPUTIL_A_ENQUEUE,      OFPAT10_ENQUEUE },
3028     { 0, 0 },
3029 };
3030
3031 static enum ofputil_action_bitmap
3032 decode_action_bits(ovs_be32 of_actions,
3033                    const struct ofputil_action_bit_translation *x)
3034 {
3035     enum ofputil_action_bitmap ofputil_actions;
3036
3037     ofputil_actions = 0;
3038     for (; x->ofputil_bit; x++) {
3039         if (of_actions & htonl(1u << x->of_bit)) {
3040             ofputil_actions |= x->ofputil_bit;
3041         }
3042     }
3043     return ofputil_actions;
3044 }
3045
3046 static uint32_t
3047 ofputil_capabilities_mask(enum ofp_version ofp_version)
3048 {
3049     /* Handle capabilities whose bit is unique for all Open Flow versions */
3050     switch (ofp_version) {
3051     case OFP10_VERSION:
3052     case OFP11_VERSION:
3053         return OFPC_COMMON | OFPC_ARP_MATCH_IP;
3054     case OFP12_VERSION:
3055     case OFP13_VERSION:
3056         return OFPC_COMMON | OFPC12_PORT_BLOCKED;
3057     default:
3058         /* Caller needs to check osf->header.version itself */
3059         return 0;
3060     }
3061 }
3062
3063 /* Decodes an OpenFlow 1.0 or 1.1 "switch_features" structure 'osf' into an
3064  * abstract representation in '*features'.  Initializes '*b' to iterate over
3065  * the OpenFlow port structures following 'osf' with later calls to
3066  * ofputil_pull_phy_port().  Returns 0 if successful, otherwise an
3067  * OFPERR_* value.  */
3068 enum ofperr
3069 ofputil_decode_switch_features(const struct ofp_header *oh,
3070                                struct ofputil_switch_features *features,
3071                                struct ofpbuf *b)
3072 {
3073     const struct ofp_switch_features *osf;
3074     enum ofpraw raw;
3075
3076     ofpbuf_use_const(b, oh, ntohs(oh->length));
3077     raw = ofpraw_pull_assert(b);
3078
3079     osf = ofpbuf_pull(b, sizeof *osf);
3080     features->datapath_id = ntohll(osf->datapath_id);
3081     features->n_buffers = ntohl(osf->n_buffers);
3082     features->n_tables = osf->n_tables;
3083     features->auxiliary_id = 0;
3084
3085     features->capabilities = ntohl(osf->capabilities) &
3086         ofputil_capabilities_mask(oh->version);
3087
3088     if (b->size % ofputil_get_phy_port_size(oh->version)) {
3089         return OFPERR_OFPBRC_BAD_LEN;
3090     }
3091
3092     if (raw == OFPRAW_OFPT10_FEATURES_REPLY) {
3093         if (osf->capabilities & htonl(OFPC10_STP)) {
3094             features->capabilities |= OFPUTIL_C_STP;
3095         }
3096         features->actions = decode_action_bits(osf->actions, of10_action_bits);
3097     } else if (raw == OFPRAW_OFPT11_FEATURES_REPLY
3098                || raw == OFPRAW_OFPT13_FEATURES_REPLY) {
3099         if (osf->capabilities & htonl(OFPC11_GROUP_STATS)) {
3100             features->capabilities |= OFPUTIL_C_GROUP_STATS;
3101         }
3102         features->actions = 0;
3103         if (raw == OFPRAW_OFPT13_FEATURES_REPLY) {
3104             features->auxiliary_id = osf->auxiliary_id;
3105         }
3106     } else {
3107         return OFPERR_OFPBRC_BAD_VERSION;
3108     }
3109
3110     return 0;
3111 }
3112
3113 /* Returns true if the maximum number of ports are in 'oh'. */
3114 static bool
3115 max_ports_in_features(const struct ofp_header *oh)
3116 {
3117     size_t pp_size = ofputil_get_phy_port_size(oh->version);
3118     return ntohs(oh->length) + pp_size > UINT16_MAX;
3119 }
3120
3121 /* Given a buffer 'b' that contains a Features Reply message, checks if
3122  * it contains the maximum number of ports that will fit.  If so, it
3123  * returns true and removes the ports from the message.  The caller
3124  * should then send an OFPST_PORT_DESC stats request to get the ports,
3125  * since the switch may have more ports than could be represented in the
3126  * Features Reply.  Otherwise, returns false.
3127  */
3128 bool
3129 ofputil_switch_features_ports_trunc(struct ofpbuf *b)
3130 {
3131     struct ofp_header *oh = b->data;
3132
3133     if (max_ports_in_features(oh)) {
3134         /* Remove all the ports. */
3135         b->size = (sizeof(struct ofp_header)
3136                    + sizeof(struct ofp_switch_features));
3137         ofpmsg_update_length(b);
3138
3139         return true;
3140     }
3141
3142     return false;
3143 }
3144
3145 static ovs_be32
3146 encode_action_bits(enum ofputil_action_bitmap ofputil_actions,
3147                    const struct ofputil_action_bit_translation *x)
3148 {
3149     uint32_t of_actions;
3150
3151     of_actions = 0;
3152     for (; x->ofputil_bit; x++) {
3153         if (ofputil_actions & x->ofputil_bit) {
3154             of_actions |= 1 << x->of_bit;
3155         }
3156     }
3157     return htonl(of_actions);
3158 }
3159
3160 /* Returns a buffer owned by the caller that encodes 'features' in the format
3161  * required by 'protocol' with the given 'xid'.  The caller should append port
3162  * information to the buffer with subsequent calls to
3163  * ofputil_put_switch_features_port(). */
3164 struct ofpbuf *
3165 ofputil_encode_switch_features(const struct ofputil_switch_features *features,
3166                                enum ofputil_protocol protocol, ovs_be32 xid)
3167 {
3168     struct ofp_switch_features *osf;
3169     struct ofpbuf *b;
3170     enum ofp_version version;
3171     enum ofpraw raw;
3172
3173     version = ofputil_protocol_to_ofp_version(protocol);
3174     switch (version) {
3175     case OFP10_VERSION:
3176         raw = OFPRAW_OFPT10_FEATURES_REPLY;
3177         break;
3178     case OFP11_VERSION:
3179     case OFP12_VERSION:
3180         raw = OFPRAW_OFPT11_FEATURES_REPLY;
3181         break;
3182     case OFP13_VERSION:
3183         raw = OFPRAW_OFPT13_FEATURES_REPLY;
3184         break;
3185     default:
3186         NOT_REACHED();
3187     }
3188     b = ofpraw_alloc_xid(raw, version, xid, 0);
3189     osf = ofpbuf_put_zeros(b, sizeof *osf);
3190     osf->datapath_id = htonll(features->datapath_id);
3191     osf->n_buffers = htonl(features->n_buffers);
3192     osf->n_tables = features->n_tables;
3193
3194     osf->capabilities = htonl(features->capabilities & OFPC_COMMON);
3195     osf->capabilities = htonl(features->capabilities &
3196                               ofputil_capabilities_mask(version));
3197     switch (version) {
3198     case OFP10_VERSION:
3199         if (features->capabilities & OFPUTIL_C_STP) {
3200             osf->capabilities |= htonl(OFPC10_STP);
3201         }
3202         osf->actions = encode_action_bits(features->actions, of10_action_bits);
3203         break;
3204     case OFP13_VERSION:
3205         osf->auxiliary_id = features->auxiliary_id;
3206         /* fall through */
3207     case OFP11_VERSION:
3208     case OFP12_VERSION:
3209         if (features->capabilities & OFPUTIL_C_GROUP_STATS) {
3210             osf->capabilities |= htonl(OFPC11_GROUP_STATS);
3211         }
3212         break;
3213     default:
3214         NOT_REACHED();
3215     }
3216
3217     return b;
3218 }
3219
3220 /* Encodes 'pp' into the format required by the switch_features message already
3221  * in 'b', which should have been returned by ofputil_encode_switch_features(),
3222  * and appends the encoded version to 'b'. */
3223 void
3224 ofputil_put_switch_features_port(const struct ofputil_phy_port *pp,
3225                                  struct ofpbuf *b)
3226 {
3227     const struct ofp_header *oh = b->data;
3228
3229     if (oh->version < OFP13_VERSION) {
3230         ofputil_put_phy_port(oh->version, pp, b);
3231     }
3232 }
3233 \f
3234 /* ofputil_port_status */
3235
3236 /* Decodes the OpenFlow "port status" message in '*ops' into an abstract form
3237  * in '*ps'.  Returns 0 if successful, otherwise an OFPERR_* value. */
3238 enum ofperr
3239 ofputil_decode_port_status(const struct ofp_header *oh,
3240                            struct ofputil_port_status *ps)
3241 {
3242     const struct ofp_port_status *ops;
3243     struct ofpbuf b;
3244     int retval;
3245
3246     ofpbuf_use_const(&b, oh, ntohs(oh->length));
3247     ofpraw_pull_assert(&b);
3248     ops = ofpbuf_pull(&b, sizeof *ops);
3249
3250     if (ops->reason != OFPPR_ADD &&
3251         ops->reason != OFPPR_DELETE &&
3252         ops->reason != OFPPR_MODIFY) {
3253         return OFPERR_NXBRC_BAD_REASON;
3254     }
3255     ps->reason = ops->reason;
3256
3257     retval = ofputil_pull_phy_port(oh->version, &b, &ps->desc);
3258     ovs_assert(retval != EOF);
3259     return retval;
3260 }
3261
3262 /* Converts the abstract form of a "port status" message in '*ps' into an
3263  * OpenFlow message suitable for 'protocol', and returns that encoded form in
3264  * a buffer owned by the caller. */
3265 struct ofpbuf *
3266 ofputil_encode_port_status(const struct ofputil_port_status *ps,
3267                            enum ofputil_protocol protocol)
3268 {
3269     struct ofp_port_status *ops;
3270     struct ofpbuf *b;
3271     enum ofp_version version;
3272     enum ofpraw raw;
3273
3274     version = ofputil_protocol_to_ofp_version(protocol);
3275     switch (version) {
3276     case OFP10_VERSION:
3277         raw = OFPRAW_OFPT10_PORT_STATUS;
3278         break;
3279
3280     case OFP11_VERSION:
3281     case OFP12_VERSION:
3282     case OFP13_VERSION:
3283         raw = OFPRAW_OFPT11_PORT_STATUS;
3284         break;
3285
3286     default:
3287         NOT_REACHED();
3288     }
3289
3290     b = ofpraw_alloc_xid(raw, version, htonl(0), 0);
3291     ops = ofpbuf_put_zeros(b, sizeof *ops);
3292     ops->reason = ps->reason;
3293     ofputil_put_phy_port(version, &ps->desc, b);
3294     ofpmsg_update_length(b);
3295     return b;
3296 }
3297 \f
3298 /* ofputil_port_mod */
3299
3300 /* Decodes the OpenFlow "port mod" message in '*oh' into an abstract form in
3301  * '*pm'.  Returns 0 if successful, otherwise an OFPERR_* value. */
3302 enum ofperr
3303 ofputil_decode_port_mod(const struct ofp_header *oh,
3304                         struct ofputil_port_mod *pm)
3305 {
3306     enum ofpraw raw;
3307     struct ofpbuf b;
3308
3309     ofpbuf_use_const(&b, oh, ntohs(oh->length));
3310     raw = ofpraw_pull_assert(&b);
3311
3312     if (raw == OFPRAW_OFPT10_PORT_MOD) {
3313         const struct ofp10_port_mod *opm = b.data;
3314
3315         pm->port_no = ntohs(opm->port_no);
3316         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
3317         pm->config = ntohl(opm->config) & OFPPC10_ALL;
3318         pm->mask = ntohl(opm->mask) & OFPPC10_ALL;
3319         pm->advertise = netdev_port_features_from_ofp10(opm->advertise);
3320     } else if (raw == OFPRAW_OFPT11_PORT_MOD) {
3321         const struct ofp11_port_mod *opm = b.data;
3322         enum ofperr error;
3323
3324         error = ofputil_port_from_ofp11(opm->port_no, &pm->port_no);
3325         if (error) {
3326             return error;
3327         }
3328
3329         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
3330         pm->config = ntohl(opm->config) & OFPPC11_ALL;
3331         pm->mask = ntohl(opm->mask) & OFPPC11_ALL;
3332         pm->advertise = netdev_port_features_from_ofp11(opm->advertise);
3333     } else {
3334         return OFPERR_OFPBRC_BAD_TYPE;
3335     }
3336
3337     pm->config &= pm->mask;
3338     return 0;
3339 }
3340
3341 /* Converts the abstract form of a "port mod" message in '*pm' into an OpenFlow
3342  * message suitable for 'protocol', and returns that encoded form in a buffer
3343  * owned by the caller. */
3344 struct ofpbuf *
3345 ofputil_encode_port_mod(const struct ofputil_port_mod *pm,
3346                         enum ofputil_protocol protocol)
3347 {
3348     enum ofp_version ofp_version = ofputil_protocol_to_ofp_version(protocol);
3349     struct ofpbuf *b;
3350
3351     switch (ofp_version) {
3352     case OFP10_VERSION: {
3353         struct ofp10_port_mod *opm;
3354
3355         b = ofpraw_alloc(OFPRAW_OFPT10_PORT_MOD, ofp_version, 0);
3356         opm = ofpbuf_put_zeros(b, sizeof *opm);
3357         opm->port_no = htons(pm->port_no);
3358         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
3359         opm->config = htonl(pm->config & OFPPC10_ALL);
3360         opm->mask = htonl(pm->mask & OFPPC10_ALL);
3361         opm->advertise = netdev_port_features_to_ofp10(pm->advertise);
3362         break;
3363     }
3364
3365     case OFP11_VERSION:
3366     case OFP12_VERSION:
3367     case OFP13_VERSION: {
3368         struct ofp11_port_mod *opm;
3369
3370         b = ofpraw_alloc(OFPRAW_OFPT11_PORT_MOD, ofp_version, 0);
3371         opm = ofpbuf_put_zeros(b, sizeof *opm);
3372         opm->port_no = ofputil_port_to_ofp11(pm->port_no);
3373         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
3374         opm->config = htonl(pm->config & OFPPC11_ALL);
3375         opm->mask = htonl(pm->mask & OFPPC11_ALL);
3376         opm->advertise = netdev_port_features_to_ofp11(pm->advertise);
3377         break;
3378     }
3379
3380     default:
3381         NOT_REACHED();
3382     }
3383
3384     return b;
3385 }
3386 \f
3387 /* ofputil_role_request */
3388
3389 /* Decodes the OpenFlow "role request" or "role reply" message in '*oh' into
3390  * an abstract form in '*rr'.  Returns 0 if successful, otherwise an
3391  * OFPERR_* value. */
3392 enum ofperr
3393 ofputil_decode_role_message(const struct ofp_header *oh,
3394                             struct ofputil_role_request *rr)
3395 {
3396     struct ofpbuf b;
3397     enum ofpraw raw;
3398
3399     ofpbuf_use_const(&b, oh, ntohs(oh->length));
3400     raw = ofpraw_pull_assert(&b);
3401
3402     if (raw == OFPRAW_OFPT12_ROLE_REQUEST ||
3403         raw == OFPRAW_OFPT12_ROLE_REPLY) {
3404         const struct ofp12_role_request *orr = b.l3;
3405
3406         if (orr->role != htonl(OFPCR12_ROLE_NOCHANGE) &&
3407             orr->role != htonl(OFPCR12_ROLE_EQUAL) &&
3408             orr->role != htonl(OFPCR12_ROLE_MASTER) &&
3409             orr->role != htonl(OFPCR12_ROLE_SLAVE)) {
3410             return OFPERR_OFPRRFC_BAD_ROLE;
3411         }
3412
3413         rr->role = ntohl(orr->role);
3414         if (raw == OFPRAW_OFPT12_ROLE_REQUEST
3415             ? orr->role == htonl(OFPCR12_ROLE_NOCHANGE)
3416             : orr->generation_id == htonll(UINT64_MAX)) {
3417             rr->have_generation_id = false;
3418             rr->generation_id = 0;
3419         } else {
3420             rr->have_generation_id = true;
3421             rr->generation_id = ntohll(orr->generation_id);
3422         }
3423     } else if (raw == OFPRAW_NXT_ROLE_REQUEST ||
3424                raw == OFPRAW_NXT_ROLE_REPLY) {
3425         const struct nx_role_request *nrr = b.l3;
3426
3427         BUILD_ASSERT(NX_ROLE_OTHER + 1 == OFPCR12_ROLE_EQUAL);
3428         BUILD_ASSERT(NX_ROLE_MASTER + 1 == OFPCR12_ROLE_MASTER);
3429         BUILD_ASSERT(NX_ROLE_SLAVE + 1 == OFPCR12_ROLE_SLAVE);
3430
3431         if (nrr->role != htonl(NX_ROLE_OTHER) &&
3432             nrr->role != htonl(NX_ROLE_MASTER) &&
3433             nrr->role != htonl(NX_ROLE_SLAVE)) {
3434             return OFPERR_OFPRRFC_BAD_ROLE;
3435         }
3436
3437         rr->role = ntohl(nrr->role) + 1;
3438         rr->have_generation_id = false;
3439         rr->generation_id = 0;
3440     } else {
3441         NOT_REACHED();
3442     }
3443
3444     return 0;
3445 }
3446
3447 /* Returns an encoded form of a role reply suitable for the "request" in a
3448  * buffer owned by the caller. */
3449 struct ofpbuf *
3450 ofputil_encode_role_reply(const struct ofp_header *request,
3451                           const struct ofputil_role_request *rr)
3452 {
3453     struct ofpbuf *buf;
3454     enum ofpraw raw;
3455
3456     raw = ofpraw_decode_assert(request);
3457     if (raw == OFPRAW_OFPT12_ROLE_REQUEST) {
3458         struct ofp12_role_request *orr;
3459
3460         buf = ofpraw_alloc_reply(OFPRAW_OFPT12_ROLE_REPLY, request, 0);
3461         orr = ofpbuf_put_zeros(buf, sizeof *orr);
3462
3463         orr->role = htonl(rr->role);
3464         orr->generation_id = htonll(rr->have_generation_id
3465                                     ? rr->generation_id
3466                                     : UINT64_MAX);
3467     } else if (raw == OFPRAW_NXT_ROLE_REQUEST) {
3468         struct nx_role_request *nrr;
3469
3470         BUILD_ASSERT(NX_ROLE_OTHER == OFPCR12_ROLE_EQUAL - 1);
3471         BUILD_ASSERT(NX_ROLE_MASTER == OFPCR12_ROLE_MASTER - 1);
3472         BUILD_ASSERT(NX_ROLE_SLAVE == OFPCR12_ROLE_SLAVE - 1);
3473
3474         buf = ofpraw_alloc_reply(OFPRAW_NXT_ROLE_REPLY, request, 0);
3475         nrr = ofpbuf_put_zeros(buf, sizeof *nrr);
3476         nrr->role = htonl(rr->role - 1);
3477     } else {
3478         NOT_REACHED();
3479     }
3480
3481     return buf;
3482 }
3483 \f
3484 /* Table stats. */
3485
3486 static void
3487 ofputil_put_ofp10_table_stats(const struct ofp12_table_stats *in,
3488                               struct ofpbuf *buf)
3489 {
3490     struct wc_map {
3491         enum ofp10_flow_wildcards wc10;
3492         enum oxm12_ofb_match_fields mf12;
3493     };
3494
3495     static const struct wc_map wc_map[] = {
3496         { OFPFW10_IN_PORT,     OFPXMT12_OFB_IN_PORT },
3497         { OFPFW10_DL_VLAN,     OFPXMT12_OFB_VLAN_VID },
3498         { OFPFW10_DL_SRC,      OFPXMT12_OFB_ETH_SRC },
3499         { OFPFW10_DL_DST,      OFPXMT12_OFB_ETH_DST},
3500         { OFPFW10_DL_TYPE,     OFPXMT12_OFB_ETH_TYPE },
3501         { OFPFW10_NW_PROTO,    OFPXMT12_OFB_IP_PROTO },
3502         { OFPFW10_TP_SRC,      OFPXMT12_OFB_TCP_SRC },
3503         { OFPFW10_TP_DST,      OFPXMT12_OFB_TCP_DST },
3504         { OFPFW10_NW_SRC_MASK, OFPXMT12_OFB_IPV4_SRC },
3505         { OFPFW10_NW_DST_MASK, OFPXMT12_OFB_IPV4_DST },
3506         { OFPFW10_DL_VLAN_PCP, OFPXMT12_OFB_VLAN_PCP },
3507         { OFPFW10_NW_TOS,      OFPXMT12_OFB_IP_DSCP },
3508     };
3509
3510     struct ofp10_table_stats *out;
3511     const struct wc_map *p;
3512
3513     out = ofpbuf_put_zeros(buf, sizeof *out);
3514     out->table_id = in->table_id;
3515     ovs_strlcpy(out->name, in->name, sizeof out->name);
3516     out->wildcards = 0;
3517     for (p = wc_map; p < &wc_map[ARRAY_SIZE(wc_map)]; p++) {
3518         if (in->wildcards & htonll(1ULL << p->mf12)) {
3519             out->wildcards |= htonl(p->wc10);
3520         }
3521     }
3522     out->max_entries = in->max_entries;
3523     out->active_count = in->active_count;
3524     put_32aligned_be64(&out->lookup_count, in->lookup_count);
3525     put_32aligned_be64(&out->matched_count, in->matched_count);
3526 }
3527
3528 static ovs_be32
3529 oxm12_to_ofp11_flow_match_fields(ovs_be64 oxm12)
3530 {
3531     struct map {
3532         enum ofp11_flow_match_fields fmf11;
3533         enum oxm12_ofb_match_fields mf12;
3534     };
3535
3536     static const struct map map[] = {
3537         { OFPFMF11_IN_PORT,     OFPXMT12_OFB_IN_PORT },
3538         { OFPFMF11_DL_VLAN,     OFPXMT12_OFB_VLAN_VID },
3539         { OFPFMF11_DL_VLAN_PCP, OFPXMT12_OFB_VLAN_PCP },
3540         { OFPFMF11_DL_TYPE,     OFPXMT12_OFB_ETH_TYPE },
3541         { OFPFMF11_NW_TOS,      OFPXMT12_OFB_IP_DSCP },
3542         { OFPFMF11_NW_PROTO,    OFPXMT12_OFB_IP_PROTO },
3543         { OFPFMF11_TP_SRC,      OFPXMT12_OFB_TCP_SRC },
3544         { OFPFMF11_TP_DST,      OFPXMT12_OFB_TCP_DST },
3545         { OFPFMF11_MPLS_LABEL,  OFPXMT12_OFB_MPLS_LABEL },
3546         { OFPFMF11_MPLS_TC,     OFPXMT12_OFB_MPLS_TC },
3547         /* I don't know what OFPFMF11_TYPE means. */
3548         { OFPFMF11_DL_SRC,      OFPXMT12_OFB_ETH_SRC },
3549         { OFPFMF11_DL_DST,      OFPXMT12_OFB_ETH_DST },
3550         { OFPFMF11_NW_SRC,      OFPXMT12_OFB_IPV4_SRC },
3551         { OFPFMF11_NW_DST,      OFPXMT12_OFB_IPV4_DST },
3552         { OFPFMF11_METADATA,    OFPXMT12_OFB_METADATA },
3553     };
3554
3555     const struct map *p;
3556     uint32_t fmf11;
3557
3558     fmf11 = 0;
3559     for (p = map; p < &map[ARRAY_SIZE(map)]; p++) {
3560         if (oxm12 & htonll(1ULL << p->mf12)) {
3561             fmf11 |= p->fmf11;
3562         }
3563     }
3564     return htonl(fmf11);
3565 }
3566
3567 static void
3568 ofputil_put_ofp11_table_stats(const struct ofp12_table_stats *in,
3569                               struct ofpbuf *buf)
3570 {
3571     struct ofp11_table_stats *out;
3572
3573     out = ofpbuf_put_zeros(buf, sizeof *out);
3574     out->table_id = in->table_id;
3575     ovs_strlcpy(out->name, in->name, sizeof out->name);
3576     out->wildcards = oxm12_to_ofp11_flow_match_fields(in->wildcards);
3577     out->match = oxm12_to_ofp11_flow_match_fields(in->match);
3578     out->instructions = in->instructions;
3579     out->write_actions = in->write_actions;
3580     out->apply_actions = in->apply_actions;
3581     out->config = in->config;
3582     out->max_entries = in->max_entries;
3583     out->active_count = in->active_count;
3584     out->lookup_count = in->lookup_count;
3585     out->matched_count = in->matched_count;
3586 }
3587
3588 static void
3589 ofputil_put_ofp13_table_stats(const struct ofp12_table_stats *in,
3590                               struct ofpbuf *buf)
3591 {
3592     struct ofp13_table_stats *out;
3593
3594     /* OF 1.3 splits table features off the ofp_table_stats,
3595      * so there is not much here. */
3596
3597     out = ofpbuf_put_uninit(buf, sizeof *out);
3598     out->table_id = in->table_id;
3599     out->active_count = in->active_count;
3600     out->lookup_count = in->lookup_count;
3601     out->matched_count = in->matched_count;
3602 }
3603
3604 struct ofpbuf *
3605 ofputil_encode_table_stats_reply(const struct ofp12_table_stats stats[], int n,
3606                                  const struct ofp_header *request)
3607 {
3608     struct ofpbuf *reply;
3609     int i;
3610
3611     reply = ofpraw_alloc_stats_reply(request, n * sizeof *stats);
3612
3613     switch ((enum ofp_version) request->version) {
3614     case OFP10_VERSION:
3615         for (i = 0; i < n; i++) {
3616             ofputil_put_ofp10_table_stats(&stats[i], reply);
3617         }
3618         break;
3619
3620     case OFP11_VERSION:
3621         for (i = 0; i < n; i++) {
3622             ofputil_put_ofp11_table_stats(&stats[i], reply);
3623         }
3624         break;
3625
3626     case OFP12_VERSION:
3627         ofpbuf_put(reply, stats, n * sizeof *stats);
3628         break;
3629
3630     case OFP13_VERSION:
3631         for (i = 0; i < n; i++) {
3632             ofputil_put_ofp13_table_stats(&stats[i], reply);
3633         }
3634         break;
3635
3636     default:
3637         NOT_REACHED();
3638     }
3639
3640     return reply;
3641 }
3642 \f
3643 /* ofputil_flow_monitor_request */
3644
3645 /* Converts an NXST_FLOW_MONITOR request in 'msg' into an abstract
3646  * ofputil_flow_monitor_request in 'rq'.
3647  *
3648  * Multiple NXST_FLOW_MONITOR requests can be packed into a single OpenFlow
3649  * message.  Calling this function multiple times for a single 'msg' iterates
3650  * through the requests.  The caller must initially leave 'msg''s layer
3651  * pointers null and not modify them between calls.
3652  *
3653  * Returns 0 if successful, EOF if no requests were left in this 'msg',
3654  * otherwise an OFPERR_* value. */
3655 int
3656 ofputil_decode_flow_monitor_request(struct ofputil_flow_monitor_request *rq,
3657                                     struct ofpbuf *msg)
3658 {
3659     struct nx_flow_monitor_request *nfmr;
3660     uint16_t flags;
3661
3662     if (!msg->l2) {
3663         msg->l2 = msg->data;
3664         ofpraw_pull_assert(msg);
3665     }
3666
3667     if (!msg->size) {
3668         return EOF;
3669     }
3670
3671     nfmr = ofpbuf_try_pull(msg, sizeof *nfmr);
3672     if (!nfmr) {
3673         VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR request has %zu "
3674                      "leftover bytes at end", msg->size);
3675         return OFPERR_OFPBRC_BAD_LEN;
3676     }
3677
3678     flags = ntohs(nfmr->flags);
3679     if (!(flags & (NXFMF_ADD | NXFMF_DELETE | NXFMF_MODIFY))
3680         || flags & ~(NXFMF_INITIAL | NXFMF_ADD | NXFMF_DELETE
3681                      | NXFMF_MODIFY | NXFMF_ACTIONS | NXFMF_OWN)) {
3682         VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR has bad flags %#"PRIx16,
3683                      flags);
3684         return OFPERR_NXBRC_FM_BAD_FLAGS;
3685     }
3686
3687     if (!is_all_zeros(nfmr->zeros, sizeof nfmr->zeros)) {
3688         return OFPERR_NXBRC_MUST_BE_ZERO;
3689     }
3690
3691     rq->id = ntohl(nfmr->id);
3692     rq->flags = flags;
3693     rq->out_port = ntohs(nfmr->out_port);
3694     rq->table_id = nfmr->table_id;
3695
3696     return nx_pull_match(msg, ntohs(nfmr->match_len), &rq->match, NULL, NULL);
3697 }
3698
3699 void
3700 ofputil_append_flow_monitor_request(
3701     const struct ofputil_flow_monitor_request *rq, struct ofpbuf *msg)
3702 {
3703     struct nx_flow_monitor_request *nfmr;
3704     size_t start_ofs;
3705     int match_len;
3706
3707     if (!msg->size) {
3708         ofpraw_put(OFPRAW_NXST_FLOW_MONITOR_REQUEST, OFP10_VERSION, msg);
3709     }
3710
3711     start_ofs = msg->size;
3712     ofpbuf_put_zeros(msg, sizeof *nfmr);
3713     match_len = nx_put_match(msg, &rq->match, htonll(0), htonll(0));
3714
3715     nfmr = ofpbuf_at_assert(msg, start_ofs, sizeof *nfmr);
3716     nfmr->id = htonl(rq->id);
3717     nfmr->flags = htons(rq->flags);
3718     nfmr->out_port = htons(rq->out_port);
3719     nfmr->match_len = htons(match_len);
3720     nfmr->table_id = rq->table_id;
3721 }
3722
3723 /* Converts an NXST_FLOW_MONITOR reply (also known as a flow update) in 'msg'
3724  * into an abstract ofputil_flow_update in 'update'.  The caller must have
3725  * initialized update->match to point to space allocated for a match.
3726  *
3727  * Uses 'ofpacts' to store the abstract OFPACT_* version of the update's
3728  * actions (except for NXFME_ABBREV, which never includes actions).  The caller
3729  * must initialize 'ofpacts' and retains ownership of it.  'update->ofpacts'
3730  * will point into the 'ofpacts' buffer.
3731  *
3732  * Multiple flow updates can be packed into a single OpenFlow message.  Calling
3733  * this function multiple times for a single 'msg' iterates through the
3734  * updates.  The caller must initially leave 'msg''s layer pointers null and
3735  * not modify them between calls.
3736  *
3737  * Returns 0 if successful, EOF if no updates were left in this 'msg',
3738  * otherwise an OFPERR_* value. */
3739 int
3740 ofputil_decode_flow_update(struct ofputil_flow_update *update,
3741                            struct ofpbuf *msg, struct ofpbuf *ofpacts)
3742 {
3743     struct nx_flow_update_header *nfuh;
3744     unsigned int length;
3745
3746     if (!msg->l2) {
3747         msg->l2 = msg->data;
3748         ofpraw_pull_assert(msg);
3749     }
3750
3751     if (!msg->size) {
3752         return EOF;
3753     }
3754
3755     if (msg->size < sizeof(struct nx_flow_update_header)) {
3756         goto bad_len;
3757     }
3758
3759     nfuh = msg->data;
3760     update->event = ntohs(nfuh->event);
3761     length = ntohs(nfuh->length);
3762     if (length > msg->size || length % 8) {
3763         goto bad_len;
3764     }
3765
3766     if (update->event == NXFME_ABBREV) {
3767         struct nx_flow_update_abbrev *nfua;
3768
3769         if (length != sizeof *nfua) {
3770             goto bad_len;
3771         }
3772
3773         nfua = ofpbuf_pull(msg, sizeof *nfua);
3774         update->xid = nfua->xid;
3775         return 0;
3776     } else if (update->event == NXFME_ADDED
3777                || update->event == NXFME_DELETED
3778                || update->event == NXFME_MODIFIED) {
3779         struct nx_flow_update_full *nfuf;
3780         unsigned int actions_len;
3781         unsigned int match_len;
3782         enum ofperr error;
3783
3784         if (length < sizeof *nfuf) {
3785             goto bad_len;
3786         }
3787
3788         nfuf = ofpbuf_pull(msg, sizeof *nfuf);
3789         match_len = ntohs(nfuf->match_len);
3790         if (sizeof *nfuf + match_len > length) {
3791             goto bad_len;
3792         }
3793
3794         update->reason = ntohs(nfuf->reason);
3795         update->idle_timeout = ntohs(nfuf->idle_timeout);
3796         update->hard_timeout = ntohs(nfuf->hard_timeout);
3797         update->table_id = nfuf->table_id;
3798         update->cookie = nfuf->cookie;
3799         update->priority = ntohs(nfuf->priority);
3800
3801         error = nx_pull_match(msg, match_len, update->match, NULL, NULL);
3802         if (error) {
3803             return error;
3804         }
3805
3806         actions_len = length - sizeof *nfuf - ROUND_UP(match_len, 8);
3807         error = ofpacts_pull_openflow10(msg, actions_len, ofpacts);
3808         if (error) {
3809             return error;
3810         }
3811
3812         update->ofpacts = ofpacts->data;
3813         update->ofpacts_len = ofpacts->size;
3814         return 0;
3815     } else {
3816         VLOG_WARN_RL(&bad_ofmsg_rl,
3817                      "NXST_FLOW_MONITOR reply has bad event %"PRIu16,
3818                      ntohs(nfuh->event));
3819         return OFPERR_NXBRC_FM_BAD_EVENT;
3820     }
3821
3822 bad_len:
3823     VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR reply has %zu "
3824                  "leftover bytes at end", msg->size);
3825     return OFPERR_OFPBRC_BAD_LEN;
3826 }
3827
3828 uint32_t
3829 ofputil_decode_flow_monitor_cancel(const struct ofp_header *oh)
3830 {
3831     const struct nx_flow_monitor_cancel *cancel = ofpmsg_body(oh);
3832
3833     return ntohl(cancel->id);
3834 }
3835
3836 struct ofpbuf *
3837 ofputil_encode_flow_monitor_cancel(uint32_t id)
3838 {
3839     struct nx_flow_monitor_cancel *nfmc;
3840     struct ofpbuf *msg;
3841
3842     msg = ofpraw_alloc(OFPRAW_NXT_FLOW_MONITOR_CANCEL, OFP10_VERSION, 0);
3843     nfmc = ofpbuf_put_uninit(msg, sizeof *nfmc);
3844     nfmc->id = htonl(id);
3845     return msg;
3846 }
3847
3848 void
3849 ofputil_start_flow_update(struct list *replies)
3850 {
3851     struct ofpbuf *msg;
3852
3853     msg = ofpraw_alloc_xid(OFPRAW_NXST_FLOW_MONITOR_REPLY, OFP10_VERSION,
3854                            htonl(0), 1024);
3855
3856     list_init(replies);
3857     list_push_back(replies, &msg->list_node);
3858 }
3859
3860 void
3861 ofputil_append_flow_update(const struct ofputil_flow_update *update,
3862                            struct list *replies)
3863 {
3864     struct nx_flow_update_header *nfuh;
3865     struct ofpbuf *msg;
3866     size_t start_ofs;
3867
3868     msg = ofpbuf_from_list(list_back(replies));
3869     start_ofs = msg->size;
3870
3871     if (update->event == NXFME_ABBREV) {
3872         struct nx_flow_update_abbrev *nfua;
3873
3874         nfua = ofpbuf_put_zeros(msg, sizeof *nfua);
3875         nfua->xid = update->xid;
3876     } else {
3877         struct nx_flow_update_full *nfuf;
3878         int match_len;
3879
3880         ofpbuf_put_zeros(msg, sizeof *nfuf);
3881         match_len = nx_put_match(msg, update->match, htonll(0), htonll(0));
3882         ofpacts_put_openflow10(update->ofpacts, update->ofpacts_len, msg);
3883
3884         nfuf = ofpbuf_at_assert(msg, start_ofs, sizeof *nfuf);
3885         nfuf->reason = htons(update->reason);
3886         nfuf->priority = htons(update->priority);
3887         nfuf->idle_timeout = htons(update->idle_timeout);
3888         nfuf->hard_timeout = htons(update->hard_timeout);
3889         nfuf->match_len = htons(match_len);
3890         nfuf->table_id = update->table_id;
3891         nfuf->cookie = update->cookie;
3892     }
3893
3894     nfuh = ofpbuf_at_assert(msg, start_ofs, sizeof *nfuh);
3895     nfuh->length = htons(msg->size - start_ofs);
3896     nfuh->event = htons(update->event);
3897
3898     ofpmp_postappend(replies, start_ofs);
3899 }
3900 \f
3901 struct ofpbuf *
3902 ofputil_encode_packet_out(const struct ofputil_packet_out *po,
3903                           enum ofputil_protocol protocol)
3904 {
3905     enum ofp_version ofp_version = ofputil_protocol_to_ofp_version(protocol);
3906     struct ofpbuf *msg;
3907     size_t size;
3908
3909     size = po->ofpacts_len;
3910     if (po->buffer_id == UINT32_MAX) {
3911         size += po->packet_len;
3912     }
3913
3914     switch (ofp_version) {
3915     case OFP10_VERSION: {
3916         struct ofp10_packet_out *opo;
3917         size_t actions_ofs;
3918
3919         msg = ofpraw_alloc(OFPRAW_OFPT10_PACKET_OUT, OFP10_VERSION, size);
3920         ofpbuf_put_zeros(msg, sizeof *opo);
3921         actions_ofs = msg->size;
3922         ofpacts_put_openflow10(po->ofpacts, po->ofpacts_len, msg);
3923
3924         opo = msg->l3;
3925         opo->buffer_id = htonl(po->buffer_id);
3926         opo->in_port = htons(po->in_port);
3927         opo->actions_len = htons(msg->size - actions_ofs);
3928         break;
3929     }
3930
3931     case OFP11_VERSION:
3932     case OFP12_VERSION:
3933     case OFP13_VERSION: {
3934         struct ofp11_packet_out *opo;
3935         size_t len;
3936
3937         msg = ofpraw_alloc(OFPRAW_OFPT11_PACKET_OUT, ofp_version, size);
3938         ofpbuf_put_zeros(msg, sizeof *opo);
3939         len = ofpacts_put_openflow11_actions(po->ofpacts, po->ofpacts_len, msg);
3940
3941         opo = msg->l3;
3942         opo->buffer_id = htonl(po->buffer_id);
3943         opo->in_port = ofputil_port_to_ofp11(po->in_port);
3944         opo->actions_len = htons(len);
3945         break;
3946     }
3947
3948     default:
3949         NOT_REACHED();
3950     }
3951
3952     if (po->buffer_id == UINT32_MAX) {
3953         ofpbuf_put(msg, po->packet, po->packet_len);
3954     }
3955
3956     ofpmsg_update_length(msg);
3957
3958     return msg;
3959 }
3960 \f
3961 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
3962 struct ofpbuf *
3963 make_echo_request(enum ofp_version ofp_version)
3964 {
3965     return ofpraw_alloc_xid(OFPRAW_OFPT_ECHO_REQUEST, ofp_version,
3966                             htonl(0), 0);
3967 }
3968
3969 /* Creates and returns an OFPT_ECHO_REPLY message matching the
3970  * OFPT_ECHO_REQUEST message in 'rq'. */
3971 struct ofpbuf *
3972 make_echo_reply(const struct ofp_header *rq)
3973 {
3974     struct ofpbuf rq_buf;
3975     struct ofpbuf *reply;
3976
3977     ofpbuf_use_const(&rq_buf, rq, ntohs(rq->length));
3978     ofpraw_pull_assert(&rq_buf);
3979
3980     reply = ofpraw_alloc_reply(OFPRAW_OFPT_ECHO_REPLY, rq, rq_buf.size);
3981     ofpbuf_put(reply, rq_buf.data, rq_buf.size);
3982     return reply;
3983 }
3984
3985 struct ofpbuf *
3986 ofputil_encode_barrier_request(enum ofp_version ofp_version)
3987 {
3988     enum ofpraw type;
3989
3990     switch (ofp_version) {
3991     case OFP13_VERSION:
3992     case OFP12_VERSION:
3993     case OFP11_VERSION:
3994         type = OFPRAW_OFPT11_BARRIER_REQUEST;
3995         break;
3996
3997     case OFP10_VERSION:
3998         type = OFPRAW_OFPT10_BARRIER_REQUEST;
3999         break;
4000
4001     default:
4002         NOT_REACHED();
4003     }
4004
4005     return ofpraw_alloc(type, ofp_version, 0);
4006 }
4007
4008 const char *
4009 ofputil_frag_handling_to_string(enum ofp_config_flags flags)
4010 {
4011     switch (flags & OFPC_FRAG_MASK) {
4012     case OFPC_FRAG_NORMAL:   return "normal";
4013     case OFPC_FRAG_DROP:     return "drop";
4014     case OFPC_FRAG_REASM:    return "reassemble";
4015     case OFPC_FRAG_NX_MATCH: return "nx-match";
4016     }
4017
4018     NOT_REACHED();
4019 }
4020
4021 bool
4022 ofputil_frag_handling_from_string(const char *s, enum ofp_config_flags *flags)
4023 {
4024     if (!strcasecmp(s, "normal")) {
4025         *flags = OFPC_FRAG_NORMAL;
4026     } else if (!strcasecmp(s, "drop")) {
4027         *flags = OFPC_FRAG_DROP;
4028     } else if (!strcasecmp(s, "reassemble")) {
4029         *flags = OFPC_FRAG_REASM;
4030     } else if (!strcasecmp(s, "nx-match")) {
4031         *flags = OFPC_FRAG_NX_MATCH;
4032     } else {
4033         return false;
4034     }
4035     return true;
4036 }
4037
4038 /* Converts the OpenFlow 1.1+ port number 'ofp11_port' into an OpenFlow 1.0
4039  * port number and stores the latter in '*ofp10_port', for the purpose of
4040  * decoding OpenFlow 1.1+ protocol messages.  Returns 0 if successful,
4041  * otherwise an OFPERR_* number.  On error, stores OFPP_NONE in '*ofp10_port'.
4042  *
4043  * See the definition of OFP11_MAX for an explanation of the mapping. */
4044 enum ofperr
4045 ofputil_port_from_ofp11(ovs_be32 ofp11_port, uint16_t *ofp10_port)
4046 {
4047     uint32_t ofp11_port_h = ntohl(ofp11_port);
4048
4049     if (ofp11_port_h < OFPP_MAX) {
4050         *ofp10_port = ofp11_port_h;
4051         return 0;
4052     } else if (ofp11_port_h >= OFPP11_MAX) {
4053         *ofp10_port = ofp11_port_h - OFPP11_OFFSET;
4054         return 0;
4055     } else {
4056         *ofp10_port = OFPP_NONE;
4057         VLOG_WARN_RL(&bad_ofmsg_rl, "port %"PRIu32" is outside the supported "
4058                      "range 0 through %d or 0x%"PRIx32" through 0x%"PRIx32,
4059                      ofp11_port_h, OFPP_MAX - 1,
4060                      (uint32_t) OFPP11_MAX, UINT32_MAX);
4061         return OFPERR_OFPBAC_BAD_OUT_PORT;
4062     }
4063 }
4064
4065 /* Returns the OpenFlow 1.1+ port number equivalent to the OpenFlow 1.0 port
4066  * number 'ofp10_port', for encoding OpenFlow 1.1+ protocol messages.
4067  *
4068  * See the definition of OFP11_MAX for an explanation of the mapping. */
4069 ovs_be32
4070 ofputil_port_to_ofp11(uint16_t ofp10_port)
4071 {
4072     return htonl(ofp10_port < OFPP_MAX
4073                  ? ofp10_port
4074                  : ofp10_port + OFPP11_OFFSET);
4075 }
4076
4077 /* Checks that 'port' is a valid output port for the OFPAT10_OUTPUT action, given
4078  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
4079  * 'port' is valid, otherwise an OpenFlow return code. */
4080 enum ofperr
4081 ofputil_check_output_port(uint16_t port, int max_ports)
4082 {
4083     switch (port) {
4084     case OFPP_IN_PORT:
4085     case OFPP_TABLE:
4086     case OFPP_NORMAL:
4087     case OFPP_FLOOD:
4088     case OFPP_ALL:
4089     case OFPP_CONTROLLER:
4090     case OFPP_NONE:
4091     case OFPP_LOCAL:
4092         return 0;
4093
4094     default:
4095         if (port < max_ports) {
4096             return 0;
4097         }
4098         return OFPERR_OFPBAC_BAD_OUT_PORT;
4099     }
4100 }
4101
4102 #define OFPUTIL_NAMED_PORTS                     \
4103         OFPUTIL_NAMED_PORT(IN_PORT)             \
4104         OFPUTIL_NAMED_PORT(TABLE)               \
4105         OFPUTIL_NAMED_PORT(NORMAL)              \
4106         OFPUTIL_NAMED_PORT(FLOOD)               \
4107         OFPUTIL_NAMED_PORT(ALL)                 \
4108         OFPUTIL_NAMED_PORT(CONTROLLER)          \
4109         OFPUTIL_NAMED_PORT(LOCAL)               \
4110         OFPUTIL_NAMED_PORT(ANY)
4111
4112 /* For backwards compatibility, so that "none" is recognized as OFPP_ANY */
4113 #define OFPUTIL_NAMED_PORTS_WITH_NONE           \
4114         OFPUTIL_NAMED_PORTS                     \
4115         OFPUTIL_NAMED_PORT(NONE)
4116
4117 /* Stores the port number represented by 's' into '*portp'.  's' may be an
4118  * integer or, for reserved ports, the standard OpenFlow name for the port
4119  * (e.g. "LOCAL").
4120  *
4121  * Returns true if successful, false if 's' is not a valid OpenFlow port number
4122  * or name.  The caller should issue an error message in this case, because
4123  * this function usually does not.  (This gives the caller an opportunity to
4124  * look up the port name another way, e.g. by contacting the switch and listing
4125  * the names of all its ports).
4126  *
4127  * This function accepts OpenFlow 1.0 port numbers.  It also accepts a subset
4128  * of OpenFlow 1.1+ port numbers, mapping those port numbers into the 16-bit
4129  * range as described in include/openflow/openflow-1.1.h. */
4130 bool
4131 ofputil_port_from_string(const char *s, uint16_t *portp)
4132 {
4133     unsigned int port32;
4134
4135     *portp = 0;
4136     if (str_to_uint(s, 10, &port32)) {
4137         if (port32 < OFPP_MAX) {
4138             *portp = port32;
4139             return true;
4140         } else if (port32 < OFPP_FIRST_RESV) {
4141             VLOG_WARN("port %u is a reserved OF1.0 port number that will "
4142                       "be translated to %u when talking to an OF1.1 or "
4143                       "later controller", port32, port32 + OFPP11_OFFSET);
4144             *portp = port32;
4145             return true;
4146         } else if (port32 <= OFPP_LAST_RESV) {
4147             struct ds msg;
4148
4149             ds_init(&msg);
4150             ofputil_format_port(port32, &msg);
4151             VLOG_WARN_ONCE("referring to port %s as %u is deprecated for "
4152                            "compatibility with future versions of OpenFlow",
4153                            ds_cstr(&msg), port32);
4154             ds_destroy(&msg);
4155
4156             *portp = port32;
4157             return true;
4158         } else if (port32 < OFPP11_MAX) {
4159             VLOG_WARN("port %u is outside the supported range 0 through "
4160                       "%"PRIx16" or 0x%x through 0x%"PRIx32, port32,
4161                       UINT16_MAX, (unsigned int) OFPP11_MAX, UINT32_MAX);
4162             return false;
4163         } else {
4164             *portp = port32 - OFPP11_OFFSET;
4165             return true;
4166         }
4167     } else {
4168         struct pair {
4169             const char *name;
4170             uint16_t value;
4171         };
4172         static const struct pair pairs[] = {
4173 #define OFPUTIL_NAMED_PORT(NAME) {#NAME, OFPP_##NAME},
4174             OFPUTIL_NAMED_PORTS_WITH_NONE
4175 #undef OFPUTIL_NAMED_PORT
4176         };
4177         const struct pair *p;
4178
4179         for (p = pairs; p < &pairs[ARRAY_SIZE(pairs)]; p++) {
4180             if (!strcasecmp(s, p->name)) {
4181                 *portp = p->value;
4182                 return true;
4183             }
4184         }
4185         return false;
4186     }
4187 }
4188
4189 /* Appends to 's' a string representation of the OpenFlow port number 'port'.
4190  * Most ports' string representation is just the port number, but for special
4191  * ports, e.g. OFPP_LOCAL, it is the name, e.g. "LOCAL". */
4192 void
4193 ofputil_format_port(uint16_t port, struct ds *s)
4194 {
4195     const char *name;
4196
4197     switch (port) {
4198 #define OFPUTIL_NAMED_PORT(NAME) case OFPP_##NAME: name = #NAME; break;
4199         OFPUTIL_NAMED_PORTS
4200 #undef OFPUTIL_NAMED_PORT
4201
4202     default:
4203         ds_put_format(s, "%"PRIu16, port);
4204         return;
4205     }
4206     ds_put_cstr(s, name);
4207 }
4208
4209 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
4210  * 'ofp_version', tries to pull the first element from the array.  If
4211  * successful, initializes '*pp' with an abstract representation of the
4212  * port and returns 0.  If no ports remain to be decoded, returns EOF.
4213  * On an error, returns a positive OFPERR_* value. */
4214 int
4215 ofputil_pull_phy_port(enum ofp_version ofp_version, struct ofpbuf *b,
4216                       struct ofputil_phy_port *pp)
4217 {
4218     switch (ofp_version) {
4219     case OFP10_VERSION: {
4220         const struct ofp10_phy_port *opp = ofpbuf_try_pull(b, sizeof *opp);
4221         return opp ? ofputil_decode_ofp10_phy_port(pp, opp) : EOF;
4222     }
4223     case OFP11_VERSION:
4224     case OFP12_VERSION:
4225     case OFP13_VERSION: {
4226         const struct ofp11_port *op = ofpbuf_try_pull(b, sizeof *op);
4227         return op ? ofputil_decode_ofp11_port(pp, op) : EOF;
4228     }
4229     default:
4230         NOT_REACHED();
4231     }
4232 }
4233
4234 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
4235  * 'ofp_version', returns the number of elements. */
4236 size_t ofputil_count_phy_ports(uint8_t ofp_version, struct ofpbuf *b)
4237 {
4238     return b->size / ofputil_get_phy_port_size(ofp_version);
4239 }
4240
4241 /* Returns the 'enum ofputil_action_code' corresponding to 'name' (e.g. if
4242  * 'name' is "output" then the return value is OFPUTIL_OFPAT10_OUTPUT), or -1 if
4243  * 'name' is not the name of any action.
4244  *
4245  * ofp-util.def lists the mapping from names to action. */
4246 int
4247 ofputil_action_code_from_name(const char *name)
4248 {
4249     static const char *const names[OFPUTIL_N_ACTIONS] = {
4250         NULL,
4251 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)             NAME,
4252 #define OFPAT11_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) NAME,
4253 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)   NAME,
4254 #include "ofp-util.def"
4255     };
4256
4257     const char *const *p;
4258
4259     for (p = names; p < &names[ARRAY_SIZE(names)]; p++) {
4260         if (*p && !strcasecmp(name, *p)) {
4261             return p - names;
4262         }
4263     }
4264     return -1;
4265 }
4266
4267 /* Appends an action of the type specified by 'code' to 'buf' and returns the
4268  * action.  Initializes the parts of 'action' that identify it as having type
4269  * <ENUM> and length 'sizeof *action' and zeros the rest.  For actions that
4270  * have variable length, the length used and cleared is that of struct
4271  * <STRUCT>.  */
4272 void *
4273 ofputil_put_action(enum ofputil_action_code code, struct ofpbuf *buf)
4274 {
4275     switch (code) {
4276     case OFPUTIL_ACTION_INVALID:
4277         NOT_REACHED();
4278
4279 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                  \
4280     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
4281 #define OFPAT11_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)      \
4282     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
4283 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)        \
4284     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
4285 #include "ofp-util.def"
4286     }
4287     NOT_REACHED();
4288 }
4289
4290 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                        \
4291     void                                                        \
4292     ofputil_init_##ENUM(struct STRUCT *s)                       \
4293     {                                                           \
4294         memset(s, 0, sizeof *s);                                \
4295         s->type = htons(ENUM);                                  \
4296         s->len = htons(sizeof *s);                              \
4297     }                                                           \
4298                                                                 \
4299     struct STRUCT *                                             \
4300     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
4301     {                                                           \
4302         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
4303         ofputil_init_##ENUM(s);                                 \
4304         return s;                                               \
4305     }
4306 #define OFPAT11_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) \
4307     OFPAT10_ACTION(ENUM, STRUCT, NAME)
4308 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)            \
4309     void                                                        \
4310     ofputil_init_##ENUM(struct STRUCT *s)                       \
4311     {                                                           \
4312         memset(s, 0, sizeof *s);                                \
4313         s->type = htons(OFPAT10_VENDOR);                        \
4314         s->len = htons(sizeof *s);                              \
4315         s->vendor = htonl(NX_VENDOR_ID);                        \
4316         s->subtype = htons(ENUM);                               \
4317     }                                                           \
4318                                                                 \
4319     struct STRUCT *                                             \
4320     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
4321     {                                                           \
4322         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
4323         ofputil_init_##ENUM(s);                                 \
4324         return s;                                               \
4325     }
4326 #include "ofp-util.def"
4327
4328 static void
4329 ofputil_normalize_match__(struct match *match, bool may_log)
4330 {
4331     enum {
4332         MAY_NW_ADDR     = 1 << 0, /* nw_src, nw_dst */
4333         MAY_TP_ADDR     = 1 << 1, /* tp_src, tp_dst */
4334         MAY_NW_PROTO    = 1 << 2, /* nw_proto */
4335         MAY_IPVx        = 1 << 3, /* tos, frag, ttl */
4336         MAY_ARP_SHA     = 1 << 4, /* arp_sha */
4337         MAY_ARP_THA     = 1 << 5, /* arp_tha */
4338         MAY_IPV6        = 1 << 6, /* ipv6_src, ipv6_dst, ipv6_label */
4339         MAY_ND_TARGET   = 1 << 7, /* nd_target */
4340         MAY_MPLS        = 1 << 8, /* mpls label and tc */
4341     } may_match;
4342
4343     struct flow_wildcards wc;
4344
4345     /* Figure out what fields may be matched. */
4346     if (match->flow.dl_type == htons(ETH_TYPE_IP)) {
4347         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_NW_ADDR;
4348         if (match->flow.nw_proto == IPPROTO_TCP ||
4349             match->flow.nw_proto == IPPROTO_UDP ||
4350             match->flow.nw_proto == IPPROTO_ICMP) {
4351             may_match |= MAY_TP_ADDR;
4352         }
4353     } else if (match->flow.dl_type == htons(ETH_TYPE_IPV6)) {
4354         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_IPV6;
4355         if (match->flow.nw_proto == IPPROTO_TCP ||
4356             match->flow.nw_proto == IPPROTO_UDP) {
4357             may_match |= MAY_TP_ADDR;
4358         } else if (match->flow.nw_proto == IPPROTO_ICMPV6) {
4359             may_match |= MAY_TP_ADDR;
4360             if (match->flow.tp_src == htons(ND_NEIGHBOR_SOLICIT)) {
4361                 may_match |= MAY_ND_TARGET | MAY_ARP_SHA;
4362             } else if (match->flow.tp_src == htons(ND_NEIGHBOR_ADVERT)) {
4363                 may_match |= MAY_ND_TARGET | MAY_ARP_THA;
4364             }
4365         }
4366     } else if (match->flow.dl_type == htons(ETH_TYPE_ARP) ||
4367                match->flow.dl_type == htons(ETH_TYPE_RARP)) {
4368         may_match = MAY_NW_PROTO | MAY_NW_ADDR | MAY_ARP_SHA | MAY_ARP_THA;
4369     } else if (eth_type_mpls(match->flow.dl_type)) {
4370         may_match = MAY_MPLS;
4371     } else {
4372         may_match = 0;
4373     }
4374
4375     /* Clear the fields that may not be matched. */
4376     wc = match->wc;
4377     if (!(may_match & MAY_NW_ADDR)) {
4378         wc.masks.nw_src = wc.masks.nw_dst = htonl(0);
4379     }
4380     if (!(may_match & MAY_TP_ADDR)) {
4381         wc.masks.tp_src = wc.masks.tp_dst = htons(0);
4382     }
4383     if (!(may_match & MAY_NW_PROTO)) {
4384         wc.masks.nw_proto = 0;
4385     }
4386     if (!(may_match & MAY_IPVx)) {
4387         wc.masks.nw_tos = 0;
4388         wc.masks.nw_ttl = 0;
4389     }
4390     if (!(may_match & MAY_ARP_SHA)) {
4391         memset(wc.masks.arp_sha, 0, ETH_ADDR_LEN);
4392     }
4393     if (!(may_match & MAY_ARP_THA)) {
4394         memset(wc.masks.arp_tha, 0, ETH_ADDR_LEN);
4395     }
4396     if (!(may_match & MAY_IPV6)) {
4397         wc.masks.ipv6_src = wc.masks.ipv6_dst = in6addr_any;
4398         wc.masks.ipv6_label = htonl(0);
4399     }
4400     if (!(may_match & MAY_ND_TARGET)) {
4401         wc.masks.nd_target = in6addr_any;
4402     }
4403     if (!(may_match & MAY_MPLS)) {
4404         wc.masks.mpls_lse = htonl(0);
4405         wc.masks.mpls_depth = 0;
4406     }
4407
4408     /* Log any changes. */
4409     if (!flow_wildcards_equal(&wc, &match->wc)) {
4410         bool log = may_log && !VLOG_DROP_INFO(&bad_ofmsg_rl);
4411         char *pre = log ? match_to_string(match, OFP_DEFAULT_PRIORITY) : NULL;
4412
4413         match->wc = wc;
4414         match_zero_wildcarded_fields(match);
4415
4416         if (log) {
4417             char *post = match_to_string(match, OFP_DEFAULT_PRIORITY);
4418             VLOG_INFO("normalization changed ofp_match, details:");
4419             VLOG_INFO(" pre: %s", pre);
4420             VLOG_INFO("post: %s", post);
4421             free(pre);
4422             free(post);
4423         }
4424     }
4425 }
4426
4427 /* "Normalizes" the wildcards in 'match'.  That means:
4428  *
4429  *    1. If the type of level N is known, then only the valid fields for that
4430  *       level may be specified.  For example, ARP does not have a TOS field,
4431  *       so nw_tos must be wildcarded if 'match' specifies an ARP flow.
4432  *       Similarly, IPv4 does not have any IPv6 addresses, so ipv6_src and
4433  *       ipv6_dst (and other fields) must be wildcarded if 'match' specifies an
4434  *       IPv4 flow.
4435  *
4436  *    2. If the type of level N is not known (or not understood by Open
4437  *       vSwitch), then no fields at all for that level may be specified.  For
4438  *       example, Open vSwitch does not understand SCTP, an L4 protocol, so the
4439  *       L4 fields tp_src and tp_dst must be wildcarded if 'match' specifies an
4440  *       SCTP flow.
4441  *
4442  * If this function changes 'match', it logs a rate-limited informational
4443  * message. */
4444 void
4445 ofputil_normalize_match(struct match *match)
4446 {
4447     ofputil_normalize_match__(match, true);
4448 }
4449
4450 /* Same as ofputil_normalize_match() without the logging.  Thus, this function
4451  * is suitable for a program's internal use, whereas ofputil_normalize_match()
4452  * sense for use on flows received from elsewhere (so that a bug in the program
4453  * that sent them can be reported and corrected). */
4454 void
4455 ofputil_normalize_match_quiet(struct match *match)
4456 {
4457     ofputil_normalize_match__(match, false);
4458 }
4459
4460 /* Parses a key or a key-value pair from '*stringp'.
4461  *
4462  * On success: Stores the key into '*keyp'.  Stores the value, if present, into
4463  * '*valuep', otherwise an empty string.  Advances '*stringp' past the end of
4464  * the key-value pair, preparing it for another call.  '*keyp' and '*valuep'
4465  * are substrings of '*stringp' created by replacing some of its bytes by null
4466  * terminators.  Returns true.
4467  *
4468  * If '*stringp' is just white space or commas, sets '*keyp' and '*valuep' to
4469  * NULL and returns false. */
4470 bool
4471 ofputil_parse_key_value(char **stringp, char **keyp, char **valuep)
4472 {
4473     char *pos, *key, *value;
4474     size_t key_len;
4475
4476     pos = *stringp;
4477     pos += strspn(pos, ", \t\r\n");
4478     if (*pos == '\0') {
4479         *keyp = *valuep = NULL;
4480         return false;
4481     }
4482
4483     key = pos;
4484     key_len = strcspn(pos, ":=(, \t\r\n");
4485     if (key[key_len] == ':' || key[key_len] == '=') {
4486         /* The value can be separated by a colon. */
4487         size_t value_len;
4488
4489         value = key + key_len + 1;
4490         value_len = strcspn(value, ", \t\r\n");
4491         pos = value + value_len + (value[value_len] != '\0');
4492         value[value_len] = '\0';
4493     } else if (key[key_len] == '(') {
4494         /* The value can be surrounded by balanced parentheses.  The outermost
4495          * set of parentheses is removed. */
4496         int level = 1;
4497         size_t value_len;
4498
4499         value = key + key_len + 1;
4500         for (value_len = 0; level > 0; value_len++) {
4501             switch (value[value_len]) {
4502             case '\0':
4503                 level = 0;
4504                 break;
4505
4506             case '(':
4507                 level++;
4508                 break;
4509
4510             case ')':
4511                 level--;
4512                 break;
4513             }
4514         }
4515         value[value_len - 1] = '\0';
4516         pos = value + value_len;
4517     } else {
4518         /* There might be no value at all. */
4519         value = key + key_len;  /* Will become the empty string below. */
4520         pos = key + key_len + (key[key_len] != '\0');
4521     }
4522     key[key_len] = '\0';
4523
4524     *stringp = pos;
4525     *keyp = key;
4526     *valuep = value;
4527     return true;
4528 }
4529
4530 /* Encode a dump ports request for 'port', the encoded message
4531  * will be for Open Flow version 'ofp_version'. Returns message
4532  * as a struct ofpbuf. Returns encoded message on success, NULL on error */
4533 struct ofpbuf *
4534 ofputil_encode_dump_ports_request(enum ofp_version ofp_version, uint16_t port)
4535 {
4536     struct ofpbuf *request;
4537
4538     switch (ofp_version) {
4539     case OFP10_VERSION: {
4540         struct ofp10_port_stats_request *req;
4541         request = ofpraw_alloc(OFPRAW_OFPST10_PORT_REQUEST, ofp_version, 0);
4542         req = ofpbuf_put_zeros(request, sizeof *req);
4543         req->port_no = htons(port);
4544         break;
4545     }
4546     case OFP11_VERSION:
4547     case OFP12_VERSION:
4548     case OFP13_VERSION: {
4549         struct ofp11_port_stats_request *req;
4550         request = ofpraw_alloc(OFPRAW_OFPST11_PORT_REQUEST, ofp_version, 0);
4551         req = ofpbuf_put_zeros(request, sizeof *req);
4552         req->port_no = ofputil_port_to_ofp11(port);
4553         break;
4554     }
4555     default:
4556         NOT_REACHED();
4557     }
4558
4559     return request;
4560 }
4561
4562 static void
4563 ofputil_port_stats_to_ofp10(const struct ofputil_port_stats *ops,
4564                             struct ofp10_port_stats *ps10)
4565 {
4566     ps10->port_no = htons(ops->port_no);
4567     memset(ps10->pad, 0, sizeof ps10->pad);
4568     put_32aligned_be64(&ps10->rx_packets, htonll(ops->stats.rx_packets));
4569     put_32aligned_be64(&ps10->tx_packets, htonll(ops->stats.tx_packets));
4570     put_32aligned_be64(&ps10->rx_bytes, htonll(ops->stats.rx_bytes));
4571     put_32aligned_be64(&ps10->tx_bytes, htonll(ops->stats.tx_bytes));
4572     put_32aligned_be64(&ps10->rx_dropped, htonll(ops->stats.rx_dropped));
4573     put_32aligned_be64(&ps10->tx_dropped, htonll(ops->stats.tx_dropped));
4574     put_32aligned_be64(&ps10->rx_errors, htonll(ops->stats.rx_errors));
4575     put_32aligned_be64(&ps10->tx_errors, htonll(ops->stats.tx_errors));
4576     put_32aligned_be64(&ps10->rx_frame_err, htonll(ops->stats.rx_frame_errors));
4577     put_32aligned_be64(&ps10->rx_over_err, htonll(ops->stats.rx_over_errors));
4578     put_32aligned_be64(&ps10->rx_crc_err, htonll(ops->stats.rx_crc_errors));
4579     put_32aligned_be64(&ps10->collisions, htonll(ops->stats.collisions));
4580 }
4581
4582 static void
4583 ofputil_port_stats_to_ofp11(const struct ofputil_port_stats *ops,
4584                             struct ofp11_port_stats *ps11)
4585 {
4586     ps11->port_no = ofputil_port_to_ofp11(ops->port_no);
4587     memset(ps11->pad, 0, sizeof ps11->pad);
4588     ps11->rx_packets = htonll(ops->stats.rx_packets);
4589     ps11->tx_packets = htonll(ops->stats.tx_packets);
4590     ps11->rx_bytes = htonll(ops->stats.rx_bytes);
4591     ps11->tx_bytes = htonll(ops->stats.tx_bytes);
4592     ps11->rx_dropped = htonll(ops->stats.rx_dropped);
4593     ps11->tx_dropped = htonll(ops->stats.tx_dropped);
4594     ps11->rx_errors = htonll(ops->stats.rx_errors);
4595     ps11->tx_errors = htonll(ops->stats.tx_errors);
4596     ps11->rx_frame_err = htonll(ops->stats.rx_frame_errors);
4597     ps11->rx_over_err = htonll(ops->stats.rx_over_errors);
4598     ps11->rx_crc_err = htonll(ops->stats.rx_crc_errors);
4599     ps11->collisions = htonll(ops->stats.collisions);
4600 }
4601
4602 static void
4603 ofputil_port_stats_to_ofp13(const struct ofputil_port_stats *ops,
4604                             struct ofp13_port_stats *ps13)
4605 {
4606     ofputil_port_stats_to_ofp11(ops, &ps13->ps);
4607     ps13->duration_sec = htonl(ops->duration_sec);
4608     ps13->duration_nsec = htonl(ops->duration_nsec);
4609 }
4610
4611
4612 /* Encode a ports stat for 'ops' and append it to 'replies'. */
4613 void
4614 ofputil_append_port_stat(struct list *replies,
4615                          const struct ofputil_port_stats *ops)
4616 {
4617     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
4618     struct ofp_header *oh = msg->data;
4619
4620     switch ((enum ofp_version)oh->version) {
4621     case OFP13_VERSION: {
4622         struct ofp13_port_stats *reply = ofpmp_append(replies, sizeof *reply);
4623         ofputil_port_stats_to_ofp13(ops, reply);
4624         break;
4625     }
4626     case OFP12_VERSION:
4627     case OFP11_VERSION: {
4628         struct ofp11_port_stats *reply = ofpmp_append(replies, sizeof *reply);
4629         ofputil_port_stats_to_ofp11(ops, reply);
4630         break;
4631     }
4632
4633     case OFP10_VERSION: {
4634         struct ofp10_port_stats *reply = ofpmp_append(replies, sizeof *reply);
4635         ofputil_port_stats_to_ofp10(ops, reply);
4636         break;
4637     }
4638
4639     default:
4640         NOT_REACHED();
4641     }
4642 }
4643
4644 static enum ofperr
4645 ofputil_port_stats_from_ofp10(struct ofputil_port_stats *ops,
4646                               const struct ofp10_port_stats *ps10)
4647 {
4648     memset(ops, 0, sizeof *ops);
4649
4650     ops->port_no = ntohs(ps10->port_no);
4651     ops->stats.rx_packets = ntohll(get_32aligned_be64(&ps10->rx_packets));
4652     ops->stats.tx_packets = ntohll(get_32aligned_be64(&ps10->tx_packets));
4653     ops->stats.rx_bytes = ntohll(get_32aligned_be64(&ps10->rx_bytes));
4654     ops->stats.tx_bytes = ntohll(get_32aligned_be64(&ps10->tx_bytes));
4655     ops->stats.rx_dropped = ntohll(get_32aligned_be64(&ps10->rx_dropped));
4656     ops->stats.tx_dropped = ntohll(get_32aligned_be64(&ps10->tx_dropped));
4657     ops->stats.rx_errors = ntohll(get_32aligned_be64(&ps10->rx_errors));
4658     ops->stats.tx_errors = ntohll(get_32aligned_be64(&ps10->tx_errors));
4659     ops->stats.rx_frame_errors =
4660         ntohll(get_32aligned_be64(&ps10->rx_frame_err));
4661     ops->stats.rx_over_errors = ntohll(get_32aligned_be64(&ps10->rx_over_err));
4662     ops->stats.rx_crc_errors = ntohll(get_32aligned_be64(&ps10->rx_crc_err));
4663     ops->stats.collisions = ntohll(get_32aligned_be64(&ps10->collisions));
4664     ops->duration_sec = ops->duration_nsec = UINT32_MAX;
4665
4666     return 0;
4667 }
4668
4669 static enum ofperr
4670 ofputil_port_stats_from_ofp11(struct ofputil_port_stats *ops,
4671                               const struct ofp11_port_stats *ps11)
4672 {
4673     enum ofperr error;
4674
4675     memset(ops, 0, sizeof *ops);
4676     error = ofputil_port_from_ofp11(ps11->port_no, &ops->port_no);
4677     if (error) {
4678         return error;
4679     }
4680
4681     ops->stats.rx_packets = ntohll(ps11->rx_packets);
4682     ops->stats.tx_packets = ntohll(ps11->tx_packets);
4683     ops->stats.rx_bytes = ntohll(ps11->rx_bytes);
4684     ops->stats.tx_bytes = ntohll(ps11->tx_bytes);
4685     ops->stats.rx_dropped = ntohll(ps11->rx_dropped);
4686     ops->stats.tx_dropped = ntohll(ps11->tx_dropped);
4687     ops->stats.rx_errors = ntohll(ps11->rx_errors);
4688     ops->stats.tx_errors = ntohll(ps11->tx_errors);
4689     ops->stats.rx_frame_errors = ntohll(ps11->rx_frame_err);
4690     ops->stats.rx_over_errors = ntohll(ps11->rx_over_err);
4691     ops->stats.rx_crc_errors = ntohll(ps11->rx_crc_err);
4692     ops->stats.collisions = ntohll(ps11->collisions);
4693     ops->duration_sec = ops->duration_nsec = UINT32_MAX;
4694
4695     return 0;
4696 }
4697
4698 static enum ofperr
4699 ofputil_port_stats_from_ofp13(struct ofputil_port_stats *ops,
4700                               const struct ofp13_port_stats *ps13)
4701 {
4702     enum ofperr error = ofputil_port_stats_from_ofp11(ops, &ps13->ps);
4703     if (!error) {
4704         ops->duration_sec = ntohl(ps13->duration_sec);
4705         ops->duration_nsec = ntohl(ps13->duration_nsec);
4706     }
4707     return error;
4708 }
4709
4710
4711 /* Returns the number of port stats elements in OFPTYPE_PORT_STATS_REPLY
4712  * message 'oh'. */
4713 size_t
4714 ofputil_count_port_stats(const struct ofp_header *oh)
4715 {
4716     struct ofpbuf b;
4717
4718     ofpbuf_use_const(&b, oh, ntohs(oh->length));
4719     ofpraw_pull_assert(&b);
4720
4721     BUILD_ASSERT(sizeof(struct ofp10_port_stats) ==
4722                  sizeof(struct ofp11_port_stats));
4723     return b.size / sizeof(struct ofp10_port_stats);
4724 }
4725
4726 /* Converts an OFPST_PORT_STATS reply in 'msg' into an abstract
4727  * ofputil_port_stats in 'ps'.
4728  *
4729  * Multiple OFPST_PORT_STATS replies can be packed into a single OpenFlow
4730  * message.  Calling this function multiple times for a single 'msg' iterates
4731  * through the replies.  The caller must initially leave 'msg''s layer pointers
4732  * null and not modify them between calls.
4733  *
4734  * Returns 0 if successful, EOF if no replies were left in this 'msg',
4735  * otherwise a positive errno value. */
4736 int
4737 ofputil_decode_port_stats(struct ofputil_port_stats *ps, struct ofpbuf *msg)
4738 {
4739     enum ofperr error;
4740     enum ofpraw raw;
4741
4742     error = (msg->l2
4743              ? ofpraw_decode(&raw, msg->l2)
4744              : ofpraw_pull(&raw, msg));
4745     if (error) {
4746         return error;
4747     }
4748
4749     if (!msg->size) {
4750         return EOF;
4751     } else if (raw == OFPRAW_OFPST13_PORT_REPLY) {
4752         const struct ofp13_port_stats *ps13;
4753
4754         ps13 = ofpbuf_try_pull(msg, sizeof *ps13);
4755         if (!ps13) {
4756             goto bad_len;
4757         }
4758         return ofputil_port_stats_from_ofp13(ps, ps13);
4759     } else if (raw == OFPRAW_OFPST11_PORT_REPLY) {
4760         const struct ofp11_port_stats *ps11;
4761
4762         ps11 = ofpbuf_try_pull(msg, sizeof *ps11);
4763         if (!ps11) {
4764             goto bad_len;
4765         }
4766         return ofputil_port_stats_from_ofp11(ps, ps11);
4767     } else if (raw == OFPRAW_OFPST10_PORT_REPLY) {
4768         const struct ofp10_port_stats *ps10;
4769
4770         ps10 = ofpbuf_try_pull(msg, sizeof *ps10);
4771         if (!ps10) {
4772             goto bad_len;
4773         }
4774         return ofputil_port_stats_from_ofp10(ps, ps10);
4775     } else {
4776         NOT_REACHED();
4777     }
4778
4779  bad_len:
4780     VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_PORT reply has %zu leftover "
4781                  "bytes at end", msg->size);
4782     return OFPERR_OFPBRC_BAD_LEN;
4783 }
4784
4785 /* Parse a port status request message into a 16 bit OpenFlow 1.0
4786  * port number and stores the latter in '*ofp10_port'.
4787  * Returns 0 if successful, otherwise an OFPERR_* number. */
4788 enum ofperr
4789 ofputil_decode_port_stats_request(const struct ofp_header *request,
4790                                   uint16_t *ofp10_port)
4791 {
4792     switch ((enum ofp_version)request->version) {
4793     case OFP13_VERSION:
4794     case OFP12_VERSION:
4795     case OFP11_VERSION: {
4796         const struct ofp11_port_stats_request *psr11 = ofpmsg_body(request);
4797         return ofputil_port_from_ofp11(psr11->port_no, ofp10_port);
4798     }
4799
4800     case OFP10_VERSION: {
4801         const struct ofp10_port_stats_request *psr10 = ofpmsg_body(request);
4802         *ofp10_port = ntohs(psr10->port_no);
4803         return 0;
4804     }
4805
4806     default:
4807         NOT_REACHED();
4808     }
4809 }
4810
4811 /* Parse a queue status request message into 'oqsr'.
4812  * Returns 0 if successful, otherwise an OFPERR_* number. */
4813 enum ofperr
4814 ofputil_decode_queue_stats_request(const struct ofp_header *request,
4815                                    struct ofputil_queue_stats_request *oqsr)
4816 {
4817     switch ((enum ofp_version)request->version) {
4818     case OFP13_VERSION:
4819     case OFP12_VERSION:
4820     case OFP11_VERSION: {
4821         const struct ofp11_queue_stats_request *qsr11 = ofpmsg_body(request);
4822         oqsr->queue_id = ntohl(qsr11->queue_id);
4823         return ofputil_port_from_ofp11(qsr11->port_no, &oqsr->port_no);
4824     }
4825
4826     case OFP10_VERSION: {
4827         const struct ofp10_queue_stats_request *qsr10 = ofpmsg_body(request);
4828         oqsr->queue_id = ntohl(qsr10->queue_id);
4829         oqsr->port_no = ntohs(qsr10->port_no);
4830         /* OF 1.0 uses OFPP_ALL for OFPP_ANY */
4831         if (oqsr->port_no == OFPP_ALL) {
4832             oqsr->port_no = OFPP_ANY;
4833         }
4834         return 0;
4835     }
4836
4837     default:
4838         NOT_REACHED();
4839     }
4840 }
4841
4842 /* Encode a queue statsrequest for 'oqsr', the encoded message
4843  * will be fore Open Flow version 'ofp_version'. Returns message
4844  * as a struct ofpbuf. Returns encoded message on success, NULL on error */
4845 struct ofpbuf *
4846 ofputil_encode_queue_stats_request(enum ofp_version ofp_version,
4847                                    const struct ofputil_queue_stats_request *oqsr)
4848 {
4849     struct ofpbuf *request;
4850
4851     switch (ofp_version) {
4852     case OFP11_VERSION:
4853     case OFP12_VERSION:
4854     case OFP13_VERSION: {
4855         struct ofp11_queue_stats_request *req;
4856         request = ofpraw_alloc(OFPRAW_OFPST11_QUEUE_REQUEST, ofp_version, 0);
4857         req = ofpbuf_put_zeros(request, sizeof *req);
4858         req->port_no = ofputil_port_to_ofp11(oqsr->port_no);
4859         req->queue_id = htonl(oqsr->queue_id);
4860         break;
4861     }
4862     case OFP10_VERSION: {
4863         struct ofp10_queue_stats_request *req;
4864         request = ofpraw_alloc(OFPRAW_OFPST10_QUEUE_REQUEST, ofp_version, 0);
4865         req = ofpbuf_put_zeros(request, sizeof *req);
4866         /* OpenFlow 1.0 needs OFPP_ALL instead of OFPP_ANY */
4867         req->port_no = htons(oqsr->port_no == OFPP_ANY
4868                              ? OFPP_ALL : oqsr->port_no);
4869         req->queue_id = htonl(oqsr->queue_id);
4870         break;
4871     }
4872     default:
4873         NOT_REACHED();
4874     }
4875
4876     return request;
4877 }
4878
4879 /* Returns the number of queue stats elements in OFPTYPE_QUEUE_STATS_REPLY
4880  * message 'oh'. */
4881 size_t
4882 ofputil_count_queue_stats(const struct ofp_header *oh)
4883 {
4884     struct ofpbuf b;
4885
4886     ofpbuf_use_const(&b, oh, ntohs(oh->length));
4887     ofpraw_pull_assert(&b);
4888
4889     BUILD_ASSERT(sizeof(struct ofp10_queue_stats) ==
4890                  sizeof(struct ofp11_queue_stats));
4891     return b.size / sizeof(struct ofp10_queue_stats);
4892 }
4893
4894 static enum ofperr
4895 ofputil_queue_stats_from_ofp10(struct ofputil_queue_stats *oqs,
4896                                const struct ofp10_queue_stats *qs10)
4897 {
4898     oqs->port_no = ntohs(qs10->port_no);
4899     oqs->queue_id = ntohl(qs10->queue_id);
4900     oqs->stats.tx_bytes = ntohll(get_32aligned_be64(&qs10->tx_bytes));
4901     oqs->stats.tx_packets = ntohll(get_32aligned_be64(&qs10->tx_packets));
4902     oqs->stats.tx_errors = ntohll(get_32aligned_be64(&qs10->tx_errors));
4903
4904     return 0;
4905 }
4906
4907 static enum ofperr
4908 ofputil_queue_stats_from_ofp11(struct ofputil_queue_stats *oqs,
4909                                const struct ofp11_queue_stats *qs11)
4910 {
4911     enum ofperr error;
4912
4913     error = ofputil_port_from_ofp11(qs11->port_no, &oqs->port_no);
4914     if (error) {
4915         return error;
4916     }
4917
4918     oqs->queue_id = ntohl(qs11->queue_id);
4919     oqs->stats.tx_bytes = ntohll(qs11->tx_bytes);
4920     oqs->stats.tx_packets = ntohll(qs11->tx_packets);
4921     oqs->stats.tx_errors = ntohll(qs11->tx_errors);
4922
4923     return 0;
4924 }
4925
4926 static enum ofperr
4927 ofputil_queue_stats_from_ofp13(struct ofputil_queue_stats *oqs,
4928                                const struct ofp13_queue_stats *qs13)
4929 {
4930     enum ofperr error
4931         = ofputil_queue_stats_from_ofp11(oqs, &qs13->qs);
4932     if (!error) {
4933         /* FIXME: Get qs13->duration_sec and qs13->duration_nsec,
4934          * Add to netdev_queue_stats? */
4935     }
4936
4937     return error;
4938 }
4939
4940 /* Converts an OFPST_QUEUE_STATS reply in 'msg' into an abstract
4941  * ofputil_queue_stats in 'qs'.
4942  *
4943  * Multiple OFPST_QUEUE_STATS replies can be packed into a single OpenFlow
4944  * message.  Calling this function multiple times for a single 'msg' iterates
4945  * through the replies.  The caller must initially leave 'msg''s layer pointers
4946  * null and not modify them between calls.
4947  *
4948  * Returns 0 if successful, EOF if no replies were left in this 'msg',
4949  * otherwise a positive errno value. */
4950 int
4951 ofputil_decode_queue_stats(struct ofputil_queue_stats *qs, struct ofpbuf *msg)
4952 {
4953     enum ofperr error;
4954     enum ofpraw raw;
4955
4956     error = (msg->l2
4957              ? ofpraw_decode(&raw, msg->l2)
4958              : ofpraw_pull(&raw, msg));
4959     if (error) {
4960         return error;
4961     }
4962
4963     if (!msg->size) {
4964         return EOF;
4965     } else if (raw == OFPRAW_OFPST13_QUEUE_REPLY) {
4966         const struct ofp13_queue_stats *qs13;
4967
4968         qs13 = ofpbuf_try_pull(msg, sizeof *qs13);
4969         if (!qs13) {
4970             goto bad_len;
4971         }
4972         return ofputil_queue_stats_from_ofp13(qs, qs13);
4973     } else if (raw == OFPRAW_OFPST11_QUEUE_REPLY) {
4974         const struct ofp11_queue_stats *qs11;
4975
4976         qs11 = ofpbuf_try_pull(msg, sizeof *qs11);
4977         if (!qs11) {
4978             goto bad_len;
4979         }
4980         return ofputil_queue_stats_from_ofp11(qs, qs11);
4981     } else if (raw == OFPRAW_OFPST10_QUEUE_REPLY) {
4982         const struct ofp10_queue_stats *qs10;
4983
4984         qs10 = ofpbuf_try_pull(msg, sizeof *qs10);
4985         if (!qs10) {
4986             goto bad_len;
4987         }
4988         return ofputil_queue_stats_from_ofp10(qs, qs10);
4989     } else {
4990         NOT_REACHED();
4991     }
4992
4993  bad_len:
4994     VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_QUEUE reply has %zu leftover "
4995                  "bytes at end", msg->size);
4996     return OFPERR_OFPBRC_BAD_LEN;
4997 }
4998
4999 static void
5000 ofputil_queue_stats_to_ofp10(const struct ofputil_queue_stats *oqs,
5001                              struct ofp10_queue_stats *qs10)
5002 {
5003     qs10->port_no = htons(oqs->port_no);
5004     memset(qs10->pad, 0, sizeof qs10->pad);
5005     qs10->queue_id = htonl(oqs->queue_id);
5006     put_32aligned_be64(&qs10->tx_bytes, htonll(oqs->stats.tx_bytes));
5007     put_32aligned_be64(&qs10->tx_packets, htonll(oqs->stats.tx_packets));
5008     put_32aligned_be64(&qs10->tx_errors, htonll(oqs->stats.tx_errors));
5009 }
5010
5011 static void
5012 ofputil_queue_stats_to_ofp11(const struct ofputil_queue_stats *oqs,
5013                              struct ofp11_queue_stats *qs11)
5014 {
5015     qs11->port_no = ofputil_port_to_ofp11(oqs->port_no);
5016     qs11->queue_id = htonl(oqs->queue_id);
5017     qs11->tx_bytes = htonll(oqs->stats.tx_bytes);
5018     qs11->tx_packets = htonll(oqs->stats.tx_packets);
5019     qs11->tx_errors = htonll(oqs->stats.tx_errors);
5020 }
5021
5022 static void
5023 ofputil_queue_stats_to_ofp13(const struct ofputil_queue_stats *oqs,
5024                              struct ofp13_queue_stats *qs13)
5025 {
5026     ofputil_queue_stats_to_ofp11(oqs, &qs13->qs);
5027     /* OF 1.3 adds duration fields */
5028     /* FIXME: Need to implement queue alive duration (sec + nsec) */
5029     qs13->duration_sec = htonl(~0);
5030     qs13->duration_nsec = htonl(~0);
5031 }
5032
5033 /* Encode a queue stat for 'oqs' and append it to 'replies'. */
5034 void
5035 ofputil_append_queue_stat(struct list *replies,
5036                           const struct ofputil_queue_stats *oqs)
5037 {
5038     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
5039     struct ofp_header *oh = msg->data;
5040
5041     switch ((enum ofp_version)oh->version) {
5042     case OFP13_VERSION: {
5043         struct ofp13_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
5044         ofputil_queue_stats_to_ofp13(oqs, reply);
5045         break;
5046     }
5047
5048     case OFP12_VERSION:
5049     case OFP11_VERSION: {
5050         struct ofp11_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
5051         ofputil_queue_stats_to_ofp11(oqs, reply);
5052         break;
5053     }
5054
5055     case OFP10_VERSION: {
5056         struct ofp10_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
5057         ofputil_queue_stats_to_ofp10(oqs, reply);
5058         break;
5059     }
5060
5061     default:
5062         NOT_REACHED();
5063     }
5064 }