2223c97cb944378cb7f9293b88062d1ce1a0b597
[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 == 22);
88
89     /* Initialize most of wc. */
90     flow_wildcards_init_catchall(wc);
91
92     if (!(ofpfw & OFPFW10_IN_PORT)) {
93         wc->masks.in_port.ofp_port = u16_to_ofp(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 = OVS_BE16_MAX;
110     }
111     if (!(ofpfw & OFPFW10_TP_DST)) {
112         wc->masks.tp_dst = OVS_BE16_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 = OVS_BE16_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.ofp_port = u16_to_ofp(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.ofp_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(ofp_to_u16(match->flow.in_port.ofp_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 'ofmatch' into a struct match in 'match'.
300  * Returns 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         ofp_port_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 = OVS_BE16_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         case IPPROTO_SCTP:
424             if (!(wc & (OFPFW11_TP_SRC))) {
425                 match_set_tp_src(match, ofmatch->tp_src);
426             }
427             if (!(wc & (OFPFW11_TP_DST))) {
428                 match_set_tp_dst(match, ofmatch->tp_dst);
429             }
430             break;
431
432         default:
433             /* OF1.1 says explicitly to ignore this. */
434             break;
435         }
436     }
437
438     if (eth_type_mpls(match->flow.dl_type)) {
439         enum { OFPFW11_MPLS_ALL = OFPFW11_MPLS_LABEL | OFPFW11_MPLS_TC };
440
441         if ((wc & OFPFW11_MPLS_ALL) != OFPFW11_MPLS_ALL) {
442             /* MPLS not supported. */
443             return OFPERR_OFPBMC_BAD_TAG;
444         }
445     }
446
447     match_set_metadata_masked(match, ofmatch->metadata,
448                               ~ofmatch->metadata_mask);
449
450     return 0;
451 }
452
453 /* Convert 'match' into the OpenFlow 1.1 match structure 'ofmatch'. */
454 void
455 ofputil_match_to_ofp11_match(const struct match *match,
456                              struct ofp11_match *ofmatch)
457 {
458     uint32_t wc = 0;
459     int i;
460
461     memset(ofmatch, 0, sizeof *ofmatch);
462     ofmatch->omh.type = htons(OFPMT_STANDARD);
463     ofmatch->omh.length = htons(OFPMT11_STANDARD_LENGTH);
464
465     if (!match->wc.masks.in_port.ofp_port) {
466         wc |= OFPFW11_IN_PORT;
467     } else {
468         ofmatch->in_port = ofputil_port_to_ofp11(match->flow.in_port.ofp_port);
469     }
470
471     memcpy(ofmatch->dl_src, match->flow.dl_src, ETH_ADDR_LEN);
472     for (i = 0; i < ETH_ADDR_LEN; i++) {
473         ofmatch->dl_src_mask[i] = ~match->wc.masks.dl_src[i];
474     }
475
476     memcpy(ofmatch->dl_dst, match->flow.dl_dst, ETH_ADDR_LEN);
477     for (i = 0; i < ETH_ADDR_LEN; i++) {
478         ofmatch->dl_dst_mask[i] = ~match->wc.masks.dl_dst[i];
479     }
480
481     if (match->wc.masks.vlan_tci == htons(0)) {
482         wc |= OFPFW11_DL_VLAN | OFPFW11_DL_VLAN_PCP;
483     } else if (match->wc.masks.vlan_tci & htons(VLAN_CFI)
484                && !(match->flow.vlan_tci & htons(VLAN_CFI))) {
485         ofmatch->dl_vlan = htons(OFPVID11_NONE);
486         wc |= OFPFW11_DL_VLAN_PCP;
487     } else {
488         if (!(match->wc.masks.vlan_tci & htons(VLAN_VID_MASK))) {
489             ofmatch->dl_vlan = htons(OFPVID11_ANY);
490         } else {
491             ofmatch->dl_vlan = htons(vlan_tci_to_vid(match->flow.vlan_tci));
492         }
493
494         if (!(match->wc.masks.vlan_tci & htons(VLAN_PCP_MASK))) {
495             wc |= OFPFW11_DL_VLAN_PCP;
496         } else {
497             ofmatch->dl_vlan_pcp = vlan_tci_to_pcp(match->flow.vlan_tci);
498         }
499     }
500
501     if (!match->wc.masks.dl_type) {
502         wc |= OFPFW11_DL_TYPE;
503     } else {
504         ofmatch->dl_type = ofputil_dl_type_to_openflow(match->flow.dl_type);
505     }
506
507     if (!(match->wc.masks.nw_tos & IP_DSCP_MASK)) {
508         wc |= OFPFW11_NW_TOS;
509     } else {
510         ofmatch->nw_tos = match->flow.nw_tos & IP_DSCP_MASK;
511     }
512
513     if (!match->wc.masks.nw_proto) {
514         wc |= OFPFW11_NW_PROTO;
515     } else {
516         ofmatch->nw_proto = match->flow.nw_proto;
517     }
518
519     ofmatch->nw_src = match->flow.nw_src;
520     ofmatch->nw_src_mask = ~match->wc.masks.nw_src;
521     ofmatch->nw_dst = match->flow.nw_dst;
522     ofmatch->nw_dst_mask = ~match->wc.masks.nw_dst;
523
524     if (!match->wc.masks.tp_src) {
525         wc |= OFPFW11_TP_SRC;
526     } else {
527         ofmatch->tp_src = match->flow.tp_src;
528     }
529
530     if (!match->wc.masks.tp_dst) {
531         wc |= OFPFW11_TP_DST;
532     } else {
533         ofmatch->tp_dst = match->flow.tp_dst;
534     }
535
536     /* MPLS not supported. */
537     wc |= OFPFW11_MPLS_LABEL;
538     wc |= OFPFW11_MPLS_TC;
539
540     ofmatch->metadata = match->flow.metadata;
541     ofmatch->metadata_mask = ~match->wc.masks.metadata;
542
543     ofmatch->wildcards = htonl(wc);
544 }
545
546 /* Returns the "typical" length of a match for 'protocol', for use in
547  * estimating space to preallocate. */
548 int
549 ofputil_match_typical_len(enum ofputil_protocol protocol)
550 {
551     switch (protocol) {
552     case OFPUTIL_P_OF10_STD:
553     case OFPUTIL_P_OF10_STD_TID:
554         return sizeof(struct ofp10_match);
555
556     case OFPUTIL_P_OF10_NXM:
557     case OFPUTIL_P_OF10_NXM_TID:
558         return NXM_TYPICAL_LEN;
559
560     case OFPUTIL_P_OF11_STD:
561         return sizeof(struct ofp11_match);
562
563     case OFPUTIL_P_OF12_OXM:
564     case OFPUTIL_P_OF13_OXM:
565         return NXM_TYPICAL_LEN;
566
567     default:
568         NOT_REACHED();
569     }
570 }
571
572 /* Appends to 'b' an struct ofp11_match_header followed by a match that
573  * expresses 'match' properly for 'protocol', plus enough zero bytes to pad the
574  * data appended out to a multiple of 8.  'protocol' must be one that is usable
575  * in OpenFlow 1.1 or later.
576  *
577  * This function can cause 'b''s data to be reallocated.
578  *
579  * Returns the number of bytes appended to 'b', excluding the padding.  Never
580  * returns zero. */
581 int
582 ofputil_put_ofp11_match(struct ofpbuf *b, const struct match *match,
583                         enum ofputil_protocol protocol)
584 {
585     switch (protocol) {
586     case OFPUTIL_P_OF10_STD:
587     case OFPUTIL_P_OF10_STD_TID:
588     case OFPUTIL_P_OF10_NXM:
589     case OFPUTIL_P_OF10_NXM_TID:
590         NOT_REACHED();
591
592     case OFPUTIL_P_OF11_STD: {
593         struct ofp11_match *om;
594
595         /* Make sure that no padding is needed. */
596         BUILD_ASSERT_DECL(sizeof *om % 8 == 0);
597
598         om = ofpbuf_put_uninit(b, sizeof *om);
599         ofputil_match_to_ofp11_match(match, om);
600         return sizeof *om;
601     }
602
603     case OFPUTIL_P_OF12_OXM:
604     case OFPUTIL_P_OF13_OXM:
605         return oxm_put_match(b, match);
606     }
607
608     NOT_REACHED();
609 }
610
611 /* Given a 'dl_type' value in the format used in struct flow, returns the
612  * corresponding 'dl_type' value for use in an ofp10_match or ofp11_match
613  * structure. */
614 ovs_be16
615 ofputil_dl_type_to_openflow(ovs_be16 flow_dl_type)
616 {
617     return (flow_dl_type == htons(FLOW_DL_TYPE_NONE)
618             ? htons(OFP_DL_TYPE_NOT_ETH_TYPE)
619             : flow_dl_type);
620 }
621
622 /* Given a 'dl_type' value in the format used in an ofp10_match or ofp11_match
623  * structure, returns the corresponding 'dl_type' value for use in struct
624  * flow. */
625 ovs_be16
626 ofputil_dl_type_from_openflow(ovs_be16 ofp_dl_type)
627 {
628     return (ofp_dl_type == htons(OFP_DL_TYPE_NOT_ETH_TYPE)
629             ? htons(FLOW_DL_TYPE_NONE)
630             : ofp_dl_type);
631 }
632 \f
633 /* Protocols. */
634
635 struct proto_abbrev {
636     enum ofputil_protocol protocol;
637     const char *name;
638 };
639
640 /* Most users really don't care about some of the differences between
641  * protocols.  These abbreviations help with that. */
642 static const struct proto_abbrev proto_abbrevs[] = {
643     { OFPUTIL_P_ANY,          "any" },
644     { OFPUTIL_P_OF10_STD_ANY, "OpenFlow10" },
645     { OFPUTIL_P_OF10_NXM_ANY, "NXM" },
646     { OFPUTIL_P_ANY_OXM,      "OXM" },
647 };
648 #define N_PROTO_ABBREVS ARRAY_SIZE(proto_abbrevs)
649
650 enum ofputil_protocol ofputil_flow_dump_protocols[] = {
651     OFPUTIL_P_OF13_OXM,
652     OFPUTIL_P_OF12_OXM,
653     OFPUTIL_P_OF11_STD,
654     OFPUTIL_P_OF10_NXM,
655     OFPUTIL_P_OF10_STD,
656 };
657 size_t ofputil_n_flow_dump_protocols = ARRAY_SIZE(ofputil_flow_dump_protocols);
658
659 /* Returns the set of ofputil_protocols that are supported with the given
660  * OpenFlow 'version'.  'version' should normally be an 8-bit OpenFlow version
661  * identifier (e.g. 0x01 for OpenFlow 1.0, 0x02 for OpenFlow 1.1).  Returns 0
662  * if 'version' is not supported or outside the valid range.  */
663 enum ofputil_protocol
664 ofputil_protocols_from_ofp_version(enum ofp_version version)
665 {
666     switch (version) {
667     case OFP10_VERSION:
668         return OFPUTIL_P_OF10_STD_ANY | OFPUTIL_P_OF10_NXM_ANY;
669     case OFP11_VERSION:
670         return OFPUTIL_P_OF11_STD;
671     case OFP12_VERSION:
672         return OFPUTIL_P_OF12_OXM;
673     case OFP13_VERSION:
674         return OFPUTIL_P_OF13_OXM;
675     default:
676         return 0;
677     }
678 }
679
680 /* Returns the ofputil_protocol that is initially in effect on an OpenFlow
681  * connection that has negotiated the given 'version'.  'version' should
682  * normally be an 8-bit OpenFlow version identifier (e.g. 0x01 for OpenFlow
683  * 1.0, 0x02 for OpenFlow 1.1).  Returns 0 if 'version' is not supported or
684  * outside the valid range.  */
685 enum ofputil_protocol
686 ofputil_protocol_from_ofp_version(enum ofp_version version)
687 {
688     return rightmost_1bit(ofputil_protocols_from_ofp_version(version));
689 }
690
691 /* Returns the OpenFlow protocol version number (e.g. OFP10_VERSION,
692  * etc.) that corresponds to 'protocol'. */
693 enum ofp_version
694 ofputil_protocol_to_ofp_version(enum ofputil_protocol protocol)
695 {
696     switch (protocol) {
697     case OFPUTIL_P_OF10_STD:
698     case OFPUTIL_P_OF10_STD_TID:
699     case OFPUTIL_P_OF10_NXM:
700     case OFPUTIL_P_OF10_NXM_TID:
701         return OFP10_VERSION;
702     case OFPUTIL_P_OF11_STD:
703         return OFP11_VERSION;
704     case OFPUTIL_P_OF12_OXM:
705         return OFP12_VERSION;
706     case OFPUTIL_P_OF13_OXM:
707         return OFP13_VERSION;
708     }
709
710     NOT_REACHED();
711 }
712
713 /* Returns a bitmap of OpenFlow versions that are supported by at
714  * least one of the 'protocols'. */
715 uint32_t
716 ofputil_protocols_to_version_bitmap(enum ofputil_protocol protocols)
717 {
718     uint32_t bitmap = 0;
719
720     for (; protocols; protocols = zero_rightmost_1bit(protocols)) {
721         enum ofputil_protocol protocol = rightmost_1bit(protocols);
722
723         bitmap |= 1u << ofputil_protocol_to_ofp_version(protocol);
724     }
725
726     return bitmap;
727 }
728
729 /* Returns the set of protocols that are supported on top of the
730  * OpenFlow versions included in 'bitmap'. */
731 enum ofputil_protocol
732 ofputil_protocols_from_version_bitmap(uint32_t bitmap)
733 {
734     enum ofputil_protocol protocols = 0;
735
736     for (; bitmap; bitmap = zero_rightmost_1bit(bitmap)) {
737         enum ofp_version version = rightmost_1bit_idx(bitmap);
738
739         protocols |= ofputil_protocols_from_ofp_version(version);
740     }
741
742     return protocols;
743 }
744
745 /* Returns true if 'protocol' is a single OFPUTIL_P_* value, false
746  * otherwise. */
747 bool
748 ofputil_protocol_is_valid(enum ofputil_protocol protocol)
749 {
750     return protocol & OFPUTIL_P_ANY && is_pow2(protocol);
751 }
752
753 /* Returns the equivalent of 'protocol' with the Nicira flow_mod_table_id
754  * extension turned on or off if 'enable' is true or false, respectively.
755  *
756  * This extension is only useful for protocols whose "standard" version does
757  * not allow specific tables to be modified.  In particular, this is true of
758  * OpenFlow 1.0.  In later versions of OpenFlow, a flow_mod request always
759  * specifies a table ID and so there is no need for such an extension.  When
760  * 'protocol' is such a protocol that doesn't need a flow_mod_table_id
761  * extension, this function just returns its 'protocol' argument unchanged
762  * regardless of the value of 'enable'.  */
763 enum ofputil_protocol
764 ofputil_protocol_set_tid(enum ofputil_protocol protocol, bool enable)
765 {
766     switch (protocol) {
767     case OFPUTIL_P_OF10_STD:
768     case OFPUTIL_P_OF10_STD_TID:
769         return enable ? OFPUTIL_P_OF10_STD_TID : OFPUTIL_P_OF10_STD;
770
771     case OFPUTIL_P_OF10_NXM:
772     case OFPUTIL_P_OF10_NXM_TID:
773         return enable ? OFPUTIL_P_OF10_NXM_TID : OFPUTIL_P_OF10_NXM;
774
775     case OFPUTIL_P_OF11_STD:
776         return OFPUTIL_P_OF11_STD;
777
778     case OFPUTIL_P_OF12_OXM:
779         return OFPUTIL_P_OF12_OXM;
780
781     case OFPUTIL_P_OF13_OXM:
782         return OFPUTIL_P_OF13_OXM;
783
784     default:
785         NOT_REACHED();
786     }
787 }
788
789 /* Returns the "base" version of 'protocol'.  That is, if 'protocol' includes
790  * some extension to a standard protocol version, the return value is the
791  * standard version of that protocol without any extension.  If 'protocol' is a
792  * standard protocol version, returns 'protocol' unchanged. */
793 enum ofputil_protocol
794 ofputil_protocol_to_base(enum ofputil_protocol protocol)
795 {
796     return ofputil_protocol_set_tid(protocol, false);
797 }
798
799 /* Returns 'new_base' with any extensions taken from 'cur'. */
800 enum ofputil_protocol
801 ofputil_protocol_set_base(enum ofputil_protocol cur,
802                           enum ofputil_protocol new_base)
803 {
804     bool tid = (cur & OFPUTIL_P_TID) != 0;
805
806     switch (new_base) {
807     case OFPUTIL_P_OF10_STD:
808     case OFPUTIL_P_OF10_STD_TID:
809         return ofputil_protocol_set_tid(OFPUTIL_P_OF10_STD, tid);
810
811     case OFPUTIL_P_OF10_NXM:
812     case OFPUTIL_P_OF10_NXM_TID:
813         return ofputil_protocol_set_tid(OFPUTIL_P_OF10_NXM, tid);
814
815     case OFPUTIL_P_OF11_STD:
816         return ofputil_protocol_set_tid(OFPUTIL_P_OF11_STD, tid);
817
818     case OFPUTIL_P_OF12_OXM:
819         return ofputil_protocol_set_tid(OFPUTIL_P_OF12_OXM, tid);
820
821     case OFPUTIL_P_OF13_OXM:
822         return ofputil_protocol_set_tid(OFPUTIL_P_OF13_OXM, tid);
823
824     default:
825         NOT_REACHED();
826     }
827 }
828
829 /* Returns a string form of 'protocol', if a simple form exists (that is, if
830  * 'protocol' is either a single protocol or it is a combination of protocols
831  * that have a single abbreviation).  Otherwise, returns NULL. */
832 const char *
833 ofputil_protocol_to_string(enum ofputil_protocol protocol)
834 {
835     const struct proto_abbrev *p;
836
837     /* Use a "switch" statement for single-bit names so that we get a compiler
838      * warning if we forget any. */
839     switch (protocol) {
840     case OFPUTIL_P_OF10_NXM:
841         return "NXM-table_id";
842
843     case OFPUTIL_P_OF10_NXM_TID:
844         return "NXM+table_id";
845
846     case OFPUTIL_P_OF10_STD:
847         return "OpenFlow10-table_id";
848
849     case OFPUTIL_P_OF10_STD_TID:
850         return "OpenFlow10+table_id";
851
852     case OFPUTIL_P_OF11_STD:
853         return "OpenFlow11";
854
855     case OFPUTIL_P_OF12_OXM:
856         return "OXM-OpenFlow12";
857
858     case OFPUTIL_P_OF13_OXM:
859         return "OXM-OpenFlow13";
860     }
861
862     /* Check abbreviations. */
863     for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
864         if (protocol == p->protocol) {
865             return p->name;
866         }
867     }
868
869     return NULL;
870 }
871
872 /* Returns a string that represents 'protocols'.  The return value might be a
873  * comma-separated list if 'protocols' doesn't have a simple name.  The return
874  * value is "none" if 'protocols' is 0.
875  *
876  * The caller must free the returned string (with free()). */
877 char *
878 ofputil_protocols_to_string(enum ofputil_protocol protocols)
879 {
880     struct ds s;
881
882     ovs_assert(!(protocols & ~OFPUTIL_P_ANY));
883     if (protocols == 0) {
884         return xstrdup("none");
885     }
886
887     ds_init(&s);
888     while (protocols) {
889         const struct proto_abbrev *p;
890         int i;
891
892         if (s.length) {
893             ds_put_char(&s, ',');
894         }
895
896         for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
897             if ((protocols & p->protocol) == p->protocol) {
898                 ds_put_cstr(&s, p->name);
899                 protocols &= ~p->protocol;
900                 goto match;
901             }
902         }
903
904         for (i = 0; i < CHAR_BIT * sizeof(enum ofputil_protocol); i++) {
905             enum ofputil_protocol bit = 1u << i;
906
907             if (protocols & bit) {
908                 ds_put_cstr(&s, ofputil_protocol_to_string(bit));
909                 protocols &= ~bit;
910                 goto match;
911             }
912         }
913         NOT_REACHED();
914
915     match: ;
916     }
917     return ds_steal_cstr(&s);
918 }
919
920 static enum ofputil_protocol
921 ofputil_protocol_from_string__(const char *s, size_t n)
922 {
923     const struct proto_abbrev *p;
924     int i;
925
926     for (i = 0; i < CHAR_BIT * sizeof(enum ofputil_protocol); i++) {
927         enum ofputil_protocol bit = 1u << i;
928         const char *name = ofputil_protocol_to_string(bit);
929
930         if (name && n == strlen(name) && !strncasecmp(s, name, n)) {
931             return bit;
932         }
933     }
934
935     for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
936         if (n == strlen(p->name) && !strncasecmp(s, p->name, n)) {
937             return p->protocol;
938         }
939     }
940
941     return 0;
942 }
943
944 /* Returns the nonempty set of protocols represented by 's', which can be a
945  * single protocol name or abbreviation or a comma-separated list of them.
946  *
947  * Aborts the program with an error message if 's' is invalid. */
948 enum ofputil_protocol
949 ofputil_protocols_from_string(const char *s)
950 {
951     const char *orig_s = s;
952     enum ofputil_protocol protocols;
953
954     protocols = 0;
955     while (*s) {
956         enum ofputil_protocol p;
957         size_t n;
958
959         n = strcspn(s, ",");
960         if (n == 0) {
961             s++;
962             continue;
963         }
964
965         p = ofputil_protocol_from_string__(s, n);
966         if (!p) {
967             ovs_fatal(0, "%.*s: unknown flow protocol", (int) n, s);
968         }
969         protocols |= p;
970
971         s += n;
972     }
973
974     if (!protocols) {
975         ovs_fatal(0, "%s: no flow protocol specified", orig_s);
976     }
977     return protocols;
978 }
979
980 static int
981 ofputil_version_from_string(const char *s)
982 {
983     if (!strcasecmp(s, "OpenFlow10")) {
984         return OFP10_VERSION;
985     }
986     if (!strcasecmp(s, "OpenFlow11")) {
987         return OFP11_VERSION;
988     }
989     if (!strcasecmp(s, "OpenFlow12")) {
990         return OFP12_VERSION;
991     }
992     if (!strcasecmp(s, "OpenFlow13")) {
993         return OFP13_VERSION;
994     }
995     return 0;
996 }
997
998 static bool
999 is_delimiter(unsigned char c)
1000 {
1001     return isspace(c) || c == ',';
1002 }
1003
1004 uint32_t
1005 ofputil_versions_from_string(const char *s)
1006 {
1007     size_t i = 0;
1008     uint32_t bitmap = 0;
1009
1010     while (s[i]) {
1011         size_t j;
1012         int version;
1013         char *key;
1014
1015         if (is_delimiter(s[i])) {
1016             i++;
1017             continue;
1018         }
1019         j = 0;
1020         while (s[i + j] && !is_delimiter(s[i + j])) {
1021             j++;
1022         }
1023         key = xmemdup0(s + i, j);
1024         version = ofputil_version_from_string(key);
1025         if (!version) {
1026             VLOG_FATAL("Unknown OpenFlow version: \"%s\"", key);
1027         }
1028         free(key);
1029         bitmap |= 1u << version;
1030         i += j;
1031     }
1032
1033     return bitmap;
1034 }
1035
1036 uint32_t
1037 ofputil_versions_from_strings(char ** const s, size_t count)
1038 {
1039     uint32_t bitmap = 0;
1040
1041     while (count--) {
1042         int version = ofputil_version_from_string(s[count]);
1043         if (!version) {
1044             VLOG_WARN("Unknown OpenFlow version: \"%s\"", s[count]);
1045         } else {
1046             bitmap |= 1u << version;
1047         }
1048     }
1049
1050     return bitmap;
1051 }
1052
1053 const char *
1054 ofputil_version_to_string(enum ofp_version ofp_version)
1055 {
1056     switch (ofp_version) {
1057     case OFP10_VERSION:
1058         return "OpenFlow10";
1059     case OFP11_VERSION:
1060         return "OpenFlow11";
1061     case OFP12_VERSION:
1062         return "OpenFlow12";
1063     case OFP13_VERSION:
1064         return "OpenFlow13";
1065     default:
1066         NOT_REACHED();
1067     }
1068 }
1069
1070 bool
1071 ofputil_packet_in_format_is_valid(enum nx_packet_in_format packet_in_format)
1072 {
1073     switch (packet_in_format) {
1074     case NXPIF_OPENFLOW10:
1075     case NXPIF_NXM:
1076         return true;
1077     }
1078
1079     return false;
1080 }
1081
1082 const char *
1083 ofputil_packet_in_format_to_string(enum nx_packet_in_format packet_in_format)
1084 {
1085     switch (packet_in_format) {
1086     case NXPIF_OPENFLOW10:
1087         return "openflow10";
1088     case NXPIF_NXM:
1089         return "nxm";
1090     default:
1091         NOT_REACHED();
1092     }
1093 }
1094
1095 int
1096 ofputil_packet_in_format_from_string(const char *s)
1097 {
1098     return (!strcmp(s, "openflow10") ? NXPIF_OPENFLOW10
1099             : !strcmp(s, "nxm") ? NXPIF_NXM
1100             : -1);
1101 }
1102
1103 void
1104 ofputil_format_version(struct ds *msg, enum ofp_version version)
1105 {
1106     ds_put_format(msg, "0x%02x", version);
1107 }
1108
1109 void
1110 ofputil_format_version_name(struct ds *msg, enum ofp_version version)
1111 {
1112     ds_put_cstr(msg, ofputil_version_to_string(version));
1113 }
1114
1115 static void
1116 ofputil_format_version_bitmap__(struct ds *msg, uint32_t bitmap,
1117                                 void (*format_version)(struct ds *msg,
1118                                                        enum ofp_version))
1119 {
1120     while (bitmap) {
1121         format_version(msg, raw_ctz(bitmap));
1122         bitmap = zero_rightmost_1bit(bitmap);
1123         if (bitmap) {
1124             ds_put_cstr(msg, ", ");
1125         }
1126     }
1127 }
1128
1129 void
1130 ofputil_format_version_bitmap(struct ds *msg, uint32_t bitmap)
1131 {
1132     ofputil_format_version_bitmap__(msg, bitmap, ofputil_format_version);
1133 }
1134
1135 void
1136 ofputil_format_version_bitmap_names(struct ds *msg, uint32_t bitmap)
1137 {
1138     ofputil_format_version_bitmap__(msg, bitmap, ofputil_format_version_name);
1139 }
1140
1141 static bool
1142 ofputil_decode_hello_bitmap(const struct ofp_hello_elem_header *oheh,
1143                             uint32_t *allowed_versionsp)
1144 {
1145     uint16_t bitmap_len = ntohs(oheh->length) - sizeof *oheh;
1146     const ovs_be32 *bitmap = ALIGNED_CAST(const ovs_be32 *, oheh + 1);
1147     uint32_t allowed_versions;
1148
1149     if (!bitmap_len || bitmap_len % sizeof *bitmap) {
1150         return false;
1151     }
1152
1153     /* Only use the first 32-bit element of the bitmap as that is all the
1154      * current implementation supports.  Subsequent elements are ignored which
1155      * should have no effect on session negotiation until Open vSwtich supports
1156      * wire-protocol versions greater than 31.
1157      */
1158     allowed_versions = ntohl(bitmap[0]);
1159
1160     if (allowed_versions & 1) {
1161         /* There's no OpenFlow version 0. */
1162         VLOG_WARN_RL(&bad_ofmsg_rl, "peer claims to support invalid OpenFlow "
1163                      "version 0x00");
1164         allowed_versions &= ~1u;
1165     }
1166
1167     if (!allowed_versions) {
1168         VLOG_WARN_RL(&bad_ofmsg_rl, "peer does not support any OpenFlow "
1169                      "version (between 0x01 and 0x1f)");
1170         return false;
1171     }
1172
1173     *allowed_versionsp = allowed_versions;
1174     return true;
1175 }
1176
1177 static uint32_t
1178 version_bitmap_from_version(uint8_t ofp_version)
1179 {
1180     return ((ofp_version < 32 ? 1u << ofp_version : 0) - 1) << 1;
1181 }
1182
1183 /* Decodes OpenFlow OFPT_HELLO message 'oh', storing into '*allowed_versions'
1184  * the set of OpenFlow versions for which 'oh' announces support.
1185  *
1186  * Because of how OpenFlow defines OFPT_HELLO messages, this function is always
1187  * successful, and thus '*allowed_versions' is always initialized.  However, it
1188  * returns false if 'oh' contains some data that could not be fully understood,
1189  * true if 'oh' was completely parsed. */
1190 bool
1191 ofputil_decode_hello(const struct ofp_header *oh, uint32_t *allowed_versions)
1192 {
1193     struct ofpbuf msg;
1194     bool ok = true;
1195
1196     ofpbuf_use_const(&msg, oh, ntohs(oh->length));
1197     ofpbuf_pull(&msg, sizeof *oh);
1198
1199     *allowed_versions = version_bitmap_from_version(oh->version);
1200     while (msg.size) {
1201         const struct ofp_hello_elem_header *oheh;
1202         unsigned int len;
1203
1204         if (msg.size < sizeof *oheh) {
1205             return false;
1206         }
1207
1208         oheh = msg.data;
1209         len = ntohs(oheh->length);
1210         if (len < sizeof *oheh || !ofpbuf_try_pull(&msg, ROUND_UP(len, 8))) {
1211             return false;
1212         }
1213
1214         if (oheh->type != htons(OFPHET_VERSIONBITMAP)
1215             || !ofputil_decode_hello_bitmap(oheh, allowed_versions)) {
1216             ok = false;
1217         }
1218     }
1219
1220     return ok;
1221 }
1222
1223 /* Returns true if 'allowed_versions' needs to be accompanied by a version
1224  * bitmap to be correctly expressed in an OFPT_HELLO message. */
1225 static bool
1226 should_send_version_bitmap(uint32_t allowed_versions)
1227 {
1228     return !is_pow2((allowed_versions >> 1) + 1);
1229 }
1230
1231 /* Create an OFPT_HELLO message that expresses support for the OpenFlow
1232  * versions in the 'allowed_versions' bitmaps and returns the message. */
1233 struct ofpbuf *
1234 ofputil_encode_hello(uint32_t allowed_versions)
1235 {
1236     enum ofp_version ofp_version;
1237     struct ofpbuf *msg;
1238
1239     ofp_version = leftmost_1bit_idx(allowed_versions);
1240     msg = ofpraw_alloc(OFPRAW_OFPT_HELLO, ofp_version, 0);
1241
1242     if (should_send_version_bitmap(allowed_versions)) {
1243         struct ofp_hello_elem_header *oheh;
1244         uint16_t map_len;
1245
1246         map_len = sizeof allowed_versions;
1247         oheh = ofpbuf_put_zeros(msg, ROUND_UP(map_len + sizeof *oheh, 8));
1248         oheh->type = htons(OFPHET_VERSIONBITMAP);
1249         oheh->length = htons(map_len + sizeof *oheh);
1250         *ALIGNED_CAST(ovs_be32 *, oheh + 1) = htonl(allowed_versions);
1251
1252         ofpmsg_update_length(msg);
1253     }
1254
1255     return msg;
1256 }
1257
1258 /* Returns an OpenFlow message that, sent on an OpenFlow connection whose
1259  * protocol is 'current', at least partly transitions the protocol to 'want'.
1260  * Stores in '*next' the protocol that will be in effect on the OpenFlow
1261  * connection if the switch processes the returned message correctly.  (If
1262  * '*next != want' then the caller will have to iterate.)
1263  *
1264  * If 'current == want', or if it is not possible to transition from 'current'
1265  * to 'want' (because, for example, 'current' and 'want' use different OpenFlow
1266  * protocol versions), returns NULL and stores 'current' in '*next'. */
1267 struct ofpbuf *
1268 ofputil_encode_set_protocol(enum ofputil_protocol current,
1269                             enum ofputil_protocol want,
1270                             enum ofputil_protocol *next)
1271 {
1272     enum ofp_version cur_version, want_version;
1273     enum ofputil_protocol cur_base, want_base;
1274     bool cur_tid, want_tid;
1275
1276     cur_version = ofputil_protocol_to_ofp_version(current);
1277     want_version = ofputil_protocol_to_ofp_version(want);
1278     if (cur_version != want_version) {
1279         *next = current;
1280         return NULL;
1281     }
1282
1283     cur_base = ofputil_protocol_to_base(current);
1284     want_base = ofputil_protocol_to_base(want);
1285     if (cur_base != want_base) {
1286         *next = ofputil_protocol_set_base(current, want_base);
1287
1288         switch (want_base) {
1289         case OFPUTIL_P_OF10_NXM:
1290             return ofputil_encode_nx_set_flow_format(NXFF_NXM);
1291
1292         case OFPUTIL_P_OF10_STD:
1293             return ofputil_encode_nx_set_flow_format(NXFF_OPENFLOW10);
1294
1295         case OFPUTIL_P_OF11_STD:
1296         case OFPUTIL_P_OF12_OXM:
1297         case OFPUTIL_P_OF13_OXM:
1298             /* There is only one variant of each OpenFlow 1.1+ protocol, and we
1299              * verified above that we're not trying to change versions. */
1300             NOT_REACHED();
1301
1302         case OFPUTIL_P_OF10_STD_TID:
1303         case OFPUTIL_P_OF10_NXM_TID:
1304             NOT_REACHED();
1305         }
1306     }
1307
1308     cur_tid = (current & OFPUTIL_P_TID) != 0;
1309     want_tid = (want & OFPUTIL_P_TID) != 0;
1310     if (cur_tid != want_tid) {
1311         *next = ofputil_protocol_set_tid(current, want_tid);
1312         return ofputil_make_flow_mod_table_id(want_tid);
1313     }
1314
1315     ovs_assert(current == want);
1316
1317     *next = current;
1318     return NULL;
1319 }
1320
1321 /* Returns an NXT_SET_FLOW_FORMAT message that can be used to set the flow
1322  * format to 'nxff'.  */
1323 struct ofpbuf *
1324 ofputil_encode_nx_set_flow_format(enum nx_flow_format nxff)
1325 {
1326     struct nx_set_flow_format *sff;
1327     struct ofpbuf *msg;
1328
1329     ovs_assert(ofputil_nx_flow_format_is_valid(nxff));
1330
1331     msg = ofpraw_alloc(OFPRAW_NXT_SET_FLOW_FORMAT, OFP10_VERSION, 0);
1332     sff = ofpbuf_put_zeros(msg, sizeof *sff);
1333     sff->format = htonl(nxff);
1334
1335     return msg;
1336 }
1337
1338 /* Returns the base protocol if 'flow_format' is a valid NXFF_* value, false
1339  * otherwise. */
1340 enum ofputil_protocol
1341 ofputil_nx_flow_format_to_protocol(enum nx_flow_format flow_format)
1342 {
1343     switch (flow_format) {
1344     case NXFF_OPENFLOW10:
1345         return OFPUTIL_P_OF10_STD;
1346
1347     case NXFF_NXM:
1348         return OFPUTIL_P_OF10_NXM;
1349
1350     default:
1351         return 0;
1352     }
1353 }
1354
1355 /* Returns true if 'flow_format' is a valid NXFF_* value, false otherwise. */
1356 bool
1357 ofputil_nx_flow_format_is_valid(enum nx_flow_format flow_format)
1358 {
1359     return ofputil_nx_flow_format_to_protocol(flow_format) != 0;
1360 }
1361
1362 /* Returns a string version of 'flow_format', which must be a valid NXFF_*
1363  * value. */
1364 const char *
1365 ofputil_nx_flow_format_to_string(enum nx_flow_format flow_format)
1366 {
1367     switch (flow_format) {
1368     case NXFF_OPENFLOW10:
1369         return "openflow10";
1370     case NXFF_NXM:
1371         return "nxm";
1372     default:
1373         NOT_REACHED();
1374     }
1375 }
1376
1377 struct ofpbuf *
1378 ofputil_make_set_packet_in_format(enum ofp_version ofp_version,
1379                                   enum nx_packet_in_format packet_in_format)
1380 {
1381     struct nx_set_packet_in_format *spif;
1382     struct ofpbuf *msg;
1383
1384     msg = ofpraw_alloc(OFPRAW_NXT_SET_PACKET_IN_FORMAT, ofp_version, 0);
1385     spif = ofpbuf_put_zeros(msg, sizeof *spif);
1386     spif->format = htonl(packet_in_format);
1387
1388     return msg;
1389 }
1390
1391 /* Returns an OpenFlow message that can be used to turn the flow_mod_table_id
1392  * extension on or off (according to 'flow_mod_table_id'). */
1393 struct ofpbuf *
1394 ofputil_make_flow_mod_table_id(bool flow_mod_table_id)
1395 {
1396     struct nx_flow_mod_table_id *nfmti;
1397     struct ofpbuf *msg;
1398
1399     msg = ofpraw_alloc(OFPRAW_NXT_FLOW_MOD_TABLE_ID, OFP10_VERSION, 0);
1400     nfmti = ofpbuf_put_zeros(msg, sizeof *nfmti);
1401     nfmti->set = flow_mod_table_id;
1402     return msg;
1403 }
1404
1405 struct ofputil_flow_mod_flag {
1406     uint16_t raw_flag;
1407     enum ofp_version min_version, max_version;
1408     enum ofputil_flow_mod_flags flag;
1409 };
1410
1411 static const struct ofputil_flow_mod_flag ofputil_flow_mod_flags[] = {
1412     { OFPFF_SEND_FLOW_REM,   OFP10_VERSION, 0, OFPUTIL_FF_SEND_FLOW_REM },
1413     { OFPFF_CHECK_OVERLAP,   OFP10_VERSION, 0, OFPUTIL_FF_CHECK_OVERLAP },
1414     { OFPFF10_EMERG,         OFP10_VERSION, OFP10_VERSION,
1415       OFPUTIL_FF_EMERG },
1416     { OFPFF12_RESET_COUNTS,  OFP12_VERSION, 0, OFPUTIL_FF_RESET_COUNTS },
1417     { OFPFF13_NO_PKT_COUNTS, OFP13_VERSION, 0, OFPUTIL_FF_NO_PKT_COUNTS },
1418     { OFPFF13_NO_BYT_COUNTS, OFP13_VERSION, 0, OFPUTIL_FF_NO_BYT_COUNTS },
1419     { 0, 0, 0, 0 },
1420 };
1421
1422 static enum ofperr
1423 ofputil_decode_flow_mod_flags(ovs_be16 raw_flags_,
1424                               enum ofp_flow_mod_command command,
1425                               enum ofp_version version,
1426                               enum ofputil_flow_mod_flags *flagsp)
1427 {
1428     uint16_t raw_flags = ntohs(raw_flags_);
1429     const struct ofputil_flow_mod_flag *f;
1430
1431     *flagsp = 0;
1432     for (f = ofputil_flow_mod_flags; f->raw_flag; f++) {
1433         if (raw_flags & f->raw_flag
1434             && version >= f->min_version
1435             && (!f->max_version || version <= f->max_version)) {
1436             raw_flags &= ~f->raw_flag;
1437             *flagsp |= f->flag;
1438         }
1439     }
1440
1441     /* In OF1.0 and OF1.1, "add" always resets counters, and other commands
1442      * never do.
1443      *
1444      * In OF1.2 and later, OFPFF12_RESET_COUNTS controls whether each command
1445      * resets counters. */
1446     if ((version == OFP10_VERSION || version == OFP11_VERSION)
1447         && command == OFPFC_ADD) {
1448         *flagsp |= OFPUTIL_FF_RESET_COUNTS;
1449     }
1450
1451     return raw_flags ? OFPERR_OFPFMFC_BAD_FLAGS : 0;
1452 }
1453
1454 static ovs_be16
1455 ofputil_encode_flow_mod_flags(enum ofputil_flow_mod_flags flags,
1456                               enum ofp_version version)
1457 {
1458     const struct ofputil_flow_mod_flag *f;
1459     uint16_t raw_flags;
1460
1461     raw_flags = 0;
1462     for (f = ofputil_flow_mod_flags; f->raw_flag; f++) {
1463         if (f->flag & flags
1464             && version >= f->min_version
1465             && (!f->max_version || version <= f->max_version)) {
1466             raw_flags |= f->raw_flag;
1467         }
1468     }
1469
1470     return htons(raw_flags);
1471 }
1472
1473 /* Converts an OFPT_FLOW_MOD or NXT_FLOW_MOD message 'oh' into an abstract
1474  * flow_mod in 'fm'.  Returns 0 if successful, otherwise an OpenFlow error
1475  * code.
1476  *
1477  * Uses 'ofpacts' to store the abstract OFPACT_* version of 'oh''s actions.
1478  * The caller must initialize 'ofpacts' and retains ownership of it.
1479  * 'fm->ofpacts' will point into the 'ofpacts' buffer.
1480  *
1481  * Does not validate the flow_mod actions.  The caller should do that, with
1482  * ofpacts_check(). */
1483 enum ofperr
1484 ofputil_decode_flow_mod(struct ofputil_flow_mod *fm,
1485                         const struct ofp_header *oh,
1486                         enum ofputil_protocol protocol,
1487                         struct ofpbuf *ofpacts)
1488 {
1489     ovs_be16 raw_flags;
1490     enum ofperr error;
1491     struct ofpbuf b;
1492     enum ofpraw raw;
1493
1494     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1495     raw = ofpraw_pull_assert(&b);
1496     if (raw == OFPRAW_OFPT11_FLOW_MOD) {
1497         /* Standard OpenFlow 1.1+ flow_mod. */
1498         const struct ofp11_flow_mod *ofm;
1499
1500         ofm = ofpbuf_pull(&b, sizeof *ofm);
1501
1502         error = ofputil_pull_ofp11_match(&b, &fm->match, NULL);
1503         if (error) {
1504             return error;
1505         }
1506
1507         error = ofpacts_pull_openflow_instructions(&b, b.size, oh->version,
1508                                                    ofpacts);
1509         if (error) {
1510             return error;
1511         }
1512
1513         /* Translate the message. */
1514         fm->priority = ntohs(ofm->priority);
1515         if (ofm->command == OFPFC_ADD
1516             || (oh->version == OFP11_VERSION
1517                 && (ofm->command == OFPFC_MODIFY ||
1518                     ofm->command == OFPFC_MODIFY_STRICT)
1519                 && ofm->cookie_mask == htonll(0))) {
1520             /* In OpenFlow 1.1 only, a "modify" or "modify-strict" that does
1521              * not match on the cookie is treated as an "add" if there is no
1522              * match. */
1523             fm->cookie = htonll(0);
1524             fm->cookie_mask = htonll(0);
1525             fm->new_cookie = ofm->cookie;
1526         } else {
1527             fm->cookie = ofm->cookie;
1528             fm->cookie_mask = ofm->cookie_mask;
1529             fm->new_cookie = OVS_BE64_MAX;
1530         }
1531         fm->modify_cookie = false;
1532         fm->command = ofm->command;
1533         fm->table_id = ofm->table_id;
1534         fm->idle_timeout = ntohs(ofm->idle_timeout);
1535         fm->hard_timeout = ntohs(ofm->hard_timeout);
1536         fm->buffer_id = ntohl(ofm->buffer_id);
1537         error = ofputil_port_from_ofp11(ofm->out_port, &fm->out_port);
1538         if (error) {
1539             return error;
1540         }
1541         fm->out_group = ntohl(ofm->out_group);
1542
1543         if ((ofm->command == OFPFC_DELETE
1544              || ofm->command == OFPFC_DELETE_STRICT)
1545             && ofm->out_group != htonl(OFPG_ANY)) {
1546             return OFPERR_OFPFMFC_UNKNOWN;
1547         }
1548         raw_flags = ofm->flags;
1549     } else {
1550         uint16_t command;
1551
1552         if (raw == OFPRAW_OFPT10_FLOW_MOD) {
1553             /* Standard OpenFlow 1.0 flow_mod. */
1554             const struct ofp10_flow_mod *ofm;
1555
1556             /* Get the ofp10_flow_mod. */
1557             ofm = ofpbuf_pull(&b, sizeof *ofm);
1558
1559             /* Translate the rule. */
1560             ofputil_match_from_ofp10_match(&ofm->match, &fm->match);
1561             ofputil_normalize_match(&fm->match);
1562
1563             /* Now get the actions. */
1564             error = ofpacts_pull_openflow_actions(&b, b.size, oh->version,
1565                                                   ofpacts);
1566             if (error) {
1567                 return error;
1568             }
1569
1570             /* OpenFlow 1.0 says that exact-match rules have to have the
1571              * highest possible priority. */
1572             fm->priority = (ofm->match.wildcards & htonl(OFPFW10_ALL)
1573                             ? ntohs(ofm->priority)
1574                             : UINT16_MAX);
1575
1576             /* Translate the message. */
1577             command = ntohs(ofm->command);
1578             fm->cookie = htonll(0);
1579             fm->cookie_mask = htonll(0);
1580             fm->new_cookie = ofm->cookie;
1581             fm->idle_timeout = ntohs(ofm->idle_timeout);
1582             fm->hard_timeout = ntohs(ofm->hard_timeout);
1583             fm->buffer_id = ntohl(ofm->buffer_id);
1584             fm->out_port = u16_to_ofp(ntohs(ofm->out_port));
1585             fm->out_group = OFPG11_ANY;
1586             raw_flags = ofm->flags;
1587         } else if (raw == OFPRAW_NXT_FLOW_MOD) {
1588             /* Nicira extended flow_mod. */
1589             const struct nx_flow_mod *nfm;
1590
1591             /* Dissect the message. */
1592             nfm = ofpbuf_pull(&b, sizeof *nfm);
1593             error = nx_pull_match(&b, ntohs(nfm->match_len),
1594                                   &fm->match, &fm->cookie, &fm->cookie_mask);
1595             if (error) {
1596                 return error;
1597             }
1598             error = ofpacts_pull_openflow_actions(&b, b.size, oh->version,
1599                                                   ofpacts);
1600             if (error) {
1601                 return error;
1602             }
1603
1604             /* Translate the message. */
1605             command = ntohs(nfm->command);
1606             if ((command & 0xff) == OFPFC_ADD && fm->cookie_mask) {
1607                 /* Flow additions may only set a new cookie, not match an
1608                  * existing cookie. */
1609                 return OFPERR_NXBRC_NXM_INVALID;
1610             }
1611             fm->priority = ntohs(nfm->priority);
1612             fm->new_cookie = nfm->cookie;
1613             fm->idle_timeout = ntohs(nfm->idle_timeout);
1614             fm->hard_timeout = ntohs(nfm->hard_timeout);
1615             fm->buffer_id = ntohl(nfm->buffer_id);
1616             fm->out_port = u16_to_ofp(ntohs(nfm->out_port));
1617             fm->out_group = OFPG11_ANY;
1618             raw_flags = nfm->flags;
1619         } else {
1620             NOT_REACHED();
1621         }
1622
1623         fm->modify_cookie = fm->new_cookie != OVS_BE64_MAX;
1624         if (protocol & OFPUTIL_P_TID) {
1625             fm->command = command & 0xff;
1626             fm->table_id = command >> 8;
1627         } else {
1628             fm->command = command;
1629             fm->table_id = 0xff;
1630         }
1631     }
1632
1633     fm->ofpacts = ofpacts->data;
1634     fm->ofpacts_len = ofpacts->size;
1635
1636     error = ofputil_decode_flow_mod_flags(raw_flags, fm->command,
1637                                           oh->version, &fm->flags);
1638     if (error) {
1639         return error;
1640     }
1641
1642     if (fm->flags & OFPUTIL_FF_EMERG) {
1643         /* We do not support the OpenFlow 1.0 emergency flow cache, which
1644          * is not required in OpenFlow 1.0.1 and removed from OpenFlow 1.1.
1645          *
1646          * OpenFlow 1.0 specifies the error code to use when idle_timeout
1647          * or hard_timeout is nonzero.  Otherwise, there is no good error
1648          * code, so just state that the flow table is full. */
1649         return (fm->hard_timeout || fm->idle_timeout
1650                 ? OFPERR_OFPFMFC_BAD_EMERG_TIMEOUT
1651                 : OFPERR_OFPFMFC_TABLE_FULL);
1652     }
1653
1654     return 0;
1655 }
1656
1657 static enum ofperr
1658 ofputil_pull_bands(struct ofpbuf *msg, size_t len, uint16_t *n_bands,
1659                    struct ofpbuf *bands)
1660 {
1661     const struct ofp13_meter_band_header *ombh;
1662     struct ofputil_meter_band *mb;
1663     uint16_t n = 0;
1664
1665     ombh = ofpbuf_try_pull(msg, len);
1666     if (!ombh) {
1667         return OFPERR_OFPBRC_BAD_LEN;
1668     }
1669
1670     while (len >= sizeof (struct ofp13_meter_band_drop)) {
1671         size_t ombh_len = ntohs(ombh->len);
1672         /* All supported band types have the same length. */
1673         if (ombh_len != sizeof (struct ofp13_meter_band_drop)) {
1674             return OFPERR_OFPBRC_BAD_LEN;
1675         }
1676         mb = ofpbuf_put_uninit(bands, sizeof *mb);
1677         mb->type = ntohs(ombh->type);
1678         mb->rate = ntohl(ombh->rate);
1679         mb->burst_size = ntohl(ombh->burst_size);
1680         mb->prec_level = (mb->type == OFPMBT13_DSCP_REMARK) ?
1681             ((struct ofp13_meter_band_dscp_remark *)ombh)->prec_level : 0;
1682         n++;
1683         len -= ombh_len;
1684         ombh = ALIGNED_CAST(struct ofp13_meter_band_header *,
1685                             (char *) ombh + ombh_len);
1686     }
1687     if (len) {
1688         return OFPERR_OFPBRC_BAD_LEN;
1689     }
1690     *n_bands = n;
1691     return 0;
1692 }
1693
1694 enum ofperr
1695 ofputil_decode_meter_mod(const struct ofp_header *oh,
1696                          struct ofputil_meter_mod *mm,
1697                          struct ofpbuf *bands)
1698 {
1699     const struct ofp13_meter_mod *omm;
1700     struct ofpbuf b;
1701
1702     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1703     ofpraw_pull_assert(&b);
1704     omm = ofpbuf_pull(&b, sizeof *omm);
1705
1706     /* Translate the message. */
1707     mm->command = ntohs(omm->command);
1708     mm->meter.meter_id = ntohl(omm->meter_id);
1709
1710     if (mm->command == OFPMC13_DELETE) {
1711         mm->meter.flags = 0;
1712         mm->meter.n_bands = 0;
1713         mm->meter.bands = NULL;
1714     } else {
1715         enum ofperr error;
1716
1717         mm->meter.flags = ntohs(omm->flags);
1718         mm->meter.bands = bands->data;
1719
1720         error = ofputil_pull_bands(&b, b.size, &mm->meter.n_bands, bands);
1721         if (error) {
1722             return error;
1723         }
1724     }
1725     return 0;
1726 }
1727
1728 void
1729 ofputil_decode_meter_request(const struct ofp_header *oh, uint32_t *meter_id)
1730 {
1731     const struct ofp13_meter_multipart_request *omr = ofpmsg_body(oh);
1732     *meter_id = ntohl(omr->meter_id);
1733 }
1734
1735 struct ofpbuf *
1736 ofputil_encode_meter_request(enum ofp_version ofp_version,
1737                              enum ofputil_meter_request_type type,
1738                              uint32_t meter_id)
1739 {
1740     struct ofpbuf *msg;
1741
1742     enum ofpraw raw;
1743
1744     switch (type) {
1745     case OFPUTIL_METER_CONFIG:
1746         raw = OFPRAW_OFPST13_METER_CONFIG_REQUEST;
1747         break;
1748     case OFPUTIL_METER_STATS:
1749         raw = OFPRAW_OFPST13_METER_REQUEST;
1750         break;
1751     default:
1752     case OFPUTIL_METER_FEATURES:
1753         raw = OFPRAW_OFPST13_METER_FEATURES_REQUEST;
1754         break;
1755     }
1756
1757     msg = ofpraw_alloc(raw, ofp_version, 0);
1758
1759     if (type != OFPUTIL_METER_FEATURES) {
1760         struct ofp13_meter_multipart_request *omr;
1761         omr = ofpbuf_put_zeros(msg, sizeof *omr);
1762         omr->meter_id = htonl(meter_id);
1763     }
1764     return msg;
1765 }
1766
1767 static void
1768 ofputil_put_bands(uint16_t n_bands, const struct ofputil_meter_band *mb,
1769                   struct ofpbuf *msg)
1770 {
1771     uint16_t n = 0;
1772
1773     for (n = 0; n < n_bands; ++n) {
1774         /* Currently all band types have same size. */
1775         struct ofp13_meter_band_dscp_remark *ombh;
1776         size_t ombh_len = sizeof *ombh;
1777
1778         ombh = ofpbuf_put_zeros(msg, ombh_len);
1779
1780         ombh->type = htons(mb->type);
1781         ombh->len = htons(ombh_len);
1782         ombh->rate = htonl(mb->rate);
1783         ombh->burst_size = htonl(mb->burst_size);
1784         ombh->prec_level = mb->prec_level;
1785
1786         mb++;
1787     }
1788 }
1789
1790 /* Encode a meter stat for 'mc' and append it to 'replies'. */
1791 void
1792 ofputil_append_meter_config(struct list *replies,
1793                             const struct ofputil_meter_config *mc)
1794 {
1795     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
1796     size_t start_ofs = msg->size;
1797     struct ofp13_meter_config *reply = ofpbuf_put_uninit(msg, sizeof *reply);
1798     reply->flags = htons(mc->flags);
1799     reply->meter_id = htonl(mc->meter_id);
1800
1801     ofputil_put_bands(mc->n_bands, mc->bands, msg);
1802
1803     reply->length = htons(msg->size - start_ofs);
1804
1805     ofpmp_postappend(replies, start_ofs);
1806 }
1807
1808 /* Encode a meter stat for 'ms' and append it to 'replies'. */
1809 void
1810 ofputil_append_meter_stats(struct list *replies,
1811                            const struct ofputil_meter_stats *ms)
1812 {
1813     struct ofp13_meter_stats *reply;
1814     uint16_t n = 0;
1815     uint16_t len;
1816
1817     len = sizeof *reply + ms->n_bands * sizeof(struct ofp13_meter_band_stats);
1818     reply = ofpmp_append(replies, len);
1819
1820     reply->meter_id = htonl(ms->meter_id);
1821     reply->len = htons(len);
1822     memset(reply->pad, 0, sizeof reply->pad);
1823     reply->flow_count = htonl(ms->flow_count);
1824     reply->packet_in_count = htonll(ms->packet_in_count);
1825     reply->byte_in_count = htonll(ms->byte_in_count);
1826     reply->duration_sec = htonl(ms->duration_sec);
1827     reply->duration_nsec = htonl(ms->duration_nsec);
1828
1829     for (n = 0; n < ms->n_bands; ++n) {
1830         const struct ofputil_meter_band_stats *src = &ms->bands[n];
1831         struct ofp13_meter_band_stats *dst = &reply->band_stats[n];
1832
1833         dst->packet_band_count = htonll(src->packet_count);
1834         dst->byte_band_count = htonll(src->byte_count);
1835     }
1836 }
1837
1838 /* Converts an OFPMP_METER_CONFIG reply in 'msg' into an abstract
1839  * ofputil_meter_config in 'mc', with mc->bands pointing to bands decoded into
1840  * 'bands'.  The caller must have initialized 'bands' and retains ownership of
1841  * it across the call.
1842  *
1843  * Multiple OFPST13_METER_CONFIG replies can be packed into a single OpenFlow
1844  * message.  Calling this function multiple times for a single 'msg' iterates
1845  * through the replies.  'bands' is cleared for each reply.
1846  *
1847  * Returns 0 if successful, EOF if no replies were left in this 'msg',
1848  * otherwise a positive errno value. */
1849 int
1850 ofputil_decode_meter_config(struct ofpbuf *msg,
1851                             struct ofputil_meter_config *mc,
1852                             struct ofpbuf *bands)
1853 {
1854     const struct ofp13_meter_config *omc;
1855     enum ofperr err;
1856
1857     /* Pull OpenFlow headers for the first call. */
1858     if (!msg->l2) {
1859         ofpraw_pull_assert(msg);
1860     }
1861
1862     if (!msg->size) {
1863         return EOF;
1864     }
1865
1866     omc = ofpbuf_try_pull(msg, sizeof *omc);
1867     if (!omc) {
1868         VLOG_WARN_RL(&bad_ofmsg_rl,
1869                      "OFPMP_METER_CONFIG reply has %zu leftover bytes at end",
1870                      msg->size);
1871         return OFPERR_OFPBRC_BAD_LEN;
1872     }
1873
1874     ofpbuf_clear(bands);
1875     err = ofputil_pull_bands(msg, ntohs(omc->length) - sizeof *omc,
1876                              &mc->n_bands, bands);
1877     if (err) {
1878         return err;
1879     }
1880     mc->meter_id = ntohl(omc->meter_id);
1881     mc->flags = ntohs(omc->flags);
1882     mc->bands = bands->data;
1883
1884     return 0;
1885 }
1886
1887 static enum ofperr
1888 ofputil_pull_band_stats(struct ofpbuf *msg, size_t len, uint16_t *n_bands,
1889                         struct ofpbuf *bands)
1890 {
1891     const struct ofp13_meter_band_stats *ombs;
1892     struct ofputil_meter_band_stats *mbs;
1893     uint16_t n, i;
1894
1895     ombs = ofpbuf_try_pull(msg, len);
1896     if (!ombs) {
1897         return OFPERR_OFPBRC_BAD_LEN;
1898     }
1899
1900     n = len / sizeof *ombs;
1901     if (len != n * sizeof *ombs) {
1902         return OFPERR_OFPBRC_BAD_LEN;
1903     }
1904
1905     mbs = ofpbuf_put_uninit(bands, len);
1906
1907     for (i = 0; i < n; ++i) {
1908         mbs[i].packet_count = ntohll(ombs[i].packet_band_count);
1909         mbs[i].byte_count = ntohll(ombs[i].byte_band_count);
1910     }
1911     *n_bands = n;
1912     return 0;
1913 }
1914
1915 /* Converts an OFPMP_METER reply in 'msg' into an abstract
1916  * ofputil_meter_stats in 'ms', with ms->bands pointing to band stats
1917  * decoded into 'bands'.
1918  *
1919  * Multiple OFPMP_METER replies can be packed into a single OpenFlow
1920  * message.  Calling this function multiple times for a single 'msg' iterates
1921  * through the replies.  'bands' is cleared for each reply.
1922  *
1923  * Returns 0 if successful, EOF if no replies were left in this 'msg',
1924  * otherwise a positive errno value. */
1925 int
1926 ofputil_decode_meter_stats(struct ofpbuf *msg,
1927                            struct ofputil_meter_stats *ms,
1928                            struct ofpbuf *bands)
1929 {
1930     const struct ofp13_meter_stats *oms;
1931     enum ofperr err;
1932
1933     /* Pull OpenFlow headers for the first call. */
1934     if (!msg->l2) {
1935         ofpraw_pull_assert(msg);
1936     }
1937
1938     if (!msg->size) {
1939         return EOF;
1940     }
1941
1942     oms = ofpbuf_try_pull(msg, sizeof *oms);
1943     if (!oms) {
1944         VLOG_WARN_RL(&bad_ofmsg_rl,
1945                      "OFPMP_METER reply has %zu leftover bytes at end",
1946                      msg->size);
1947         return OFPERR_OFPBRC_BAD_LEN;
1948     }
1949
1950     ofpbuf_clear(bands);
1951     err = ofputil_pull_band_stats(msg, ntohs(oms->len) - sizeof *oms,
1952                                   &ms->n_bands, bands);
1953     if (err) {
1954         return err;
1955     }
1956     ms->meter_id = ntohl(oms->meter_id);
1957     ms->flow_count = ntohl(oms->flow_count);
1958     ms->packet_in_count = ntohll(oms->packet_in_count);
1959     ms->byte_in_count = ntohll(oms->byte_in_count);
1960     ms->duration_sec = ntohl(oms->duration_sec);
1961     ms->duration_nsec = ntohl(oms->duration_nsec);
1962     ms->bands = bands->data;
1963
1964     return 0;
1965 }
1966
1967 void
1968 ofputil_decode_meter_features(const struct ofp_header *oh,
1969                               struct ofputil_meter_features *mf)
1970 {
1971     const struct ofp13_meter_features *omf = ofpmsg_body(oh);
1972
1973     mf->max_meters = ntohl(omf->max_meter);
1974     mf->band_types = ntohl(omf->band_types);
1975     mf->capabilities = ntohl(omf->capabilities);
1976     mf->max_bands = omf->max_bands;
1977     mf->max_color = omf->max_color;
1978 }
1979
1980 struct ofpbuf *
1981 ofputil_encode_meter_features_reply(const struct ofputil_meter_features *mf,
1982                                     const struct ofp_header *request)
1983 {
1984     struct ofpbuf *reply;
1985     struct ofp13_meter_features *omf;
1986
1987     reply = ofpraw_alloc_stats_reply(request, 0);
1988     omf = ofpbuf_put_zeros(reply, sizeof *omf);
1989
1990     omf->max_meter = htonl(mf->max_meters);
1991     omf->band_types = htonl(mf->band_types);
1992     omf->capabilities = htonl(mf->capabilities);
1993     omf->max_bands = mf->max_bands;
1994     omf->max_color = mf->max_color;
1995
1996     return reply;
1997 }
1998
1999 struct ofpbuf *
2000 ofputil_encode_meter_mod(enum ofp_version ofp_version,
2001                          const struct ofputil_meter_mod *mm)
2002 {
2003     struct ofpbuf *msg;
2004
2005     struct ofp13_meter_mod *omm;
2006
2007     msg = ofpraw_alloc(OFPRAW_OFPT13_METER_MOD, ofp_version,
2008                        NXM_TYPICAL_LEN + mm->meter.n_bands * 16);
2009     omm = ofpbuf_put_zeros(msg, sizeof *omm);
2010     omm->command = htons(mm->command);
2011     if (mm->command != OFPMC13_DELETE) {
2012         omm->flags = htons(mm->meter.flags);
2013     }
2014     omm->meter_id = htonl(mm->meter.meter_id);
2015
2016     ofputil_put_bands(mm->meter.n_bands, mm->meter.bands, msg);
2017
2018     ofpmsg_update_length(msg);
2019     return msg;
2020 }
2021
2022 static ovs_be16
2023 ofputil_tid_command(const struct ofputil_flow_mod *fm,
2024                     enum ofputil_protocol protocol)
2025 {
2026     return htons(protocol & OFPUTIL_P_TID
2027                  ? (fm->command & 0xff) | (fm->table_id << 8)
2028                  : fm->command);
2029 }
2030
2031 /* Converts 'fm' into an OFPT_FLOW_MOD or NXT_FLOW_MOD message according to
2032  * 'protocol' and returns the message. */
2033 struct ofpbuf *
2034 ofputil_encode_flow_mod(const struct ofputil_flow_mod *fm,
2035                         enum ofputil_protocol protocol)
2036 {
2037     enum ofp_version version = ofputil_protocol_to_ofp_version(protocol);
2038     ovs_be16 raw_flags = ofputil_encode_flow_mod_flags(fm->flags, version);
2039     struct ofpbuf *msg;
2040
2041     switch (protocol) {
2042     case OFPUTIL_P_OF11_STD:
2043     case OFPUTIL_P_OF12_OXM:
2044     case OFPUTIL_P_OF13_OXM: {
2045         struct ofp11_flow_mod *ofm;
2046         int tailroom;
2047
2048         tailroom = ofputil_match_typical_len(protocol) + fm->ofpacts_len;
2049         msg = ofpraw_alloc(OFPRAW_OFPT11_FLOW_MOD, version, tailroom);
2050         ofm = ofpbuf_put_zeros(msg, sizeof *ofm);
2051         if ((protocol == OFPUTIL_P_OF11_STD
2052              && (fm->command == OFPFC_MODIFY ||
2053                  fm->command == OFPFC_MODIFY_STRICT)
2054              && fm->cookie_mask == htonll(0))
2055             || fm->command == OFPFC_ADD) {
2056             ofm->cookie = fm->new_cookie;
2057         } else {
2058             ofm->cookie = fm->cookie;
2059         }
2060         ofm->cookie_mask = fm->cookie_mask;
2061         ofm->table_id = fm->table_id;
2062         ofm->command = fm->command;
2063         ofm->idle_timeout = htons(fm->idle_timeout);
2064         ofm->hard_timeout = htons(fm->hard_timeout);
2065         ofm->priority = htons(fm->priority);
2066         ofm->buffer_id = htonl(fm->buffer_id);
2067         ofm->out_port = ofputil_port_to_ofp11(fm->out_port);
2068         ofm->out_group = htonl(fm->out_group);
2069         ofm->flags = raw_flags;
2070         ofputil_put_ofp11_match(msg, &fm->match, protocol);
2071         ofpacts_put_openflow_instructions(fm->ofpacts, fm->ofpacts_len, msg,
2072                                           version);
2073         break;
2074     }
2075
2076     case OFPUTIL_P_OF10_STD:
2077     case OFPUTIL_P_OF10_STD_TID: {
2078         struct ofp10_flow_mod *ofm;
2079
2080         msg = ofpraw_alloc(OFPRAW_OFPT10_FLOW_MOD, OFP10_VERSION,
2081                            fm->ofpacts_len);
2082         ofm = ofpbuf_put_zeros(msg, sizeof *ofm);
2083         ofputil_match_to_ofp10_match(&fm->match, &ofm->match);
2084         ofm->cookie = fm->new_cookie;
2085         ofm->command = ofputil_tid_command(fm, protocol);
2086         ofm->idle_timeout = htons(fm->idle_timeout);
2087         ofm->hard_timeout = htons(fm->hard_timeout);
2088         ofm->priority = htons(fm->priority);
2089         ofm->buffer_id = htonl(fm->buffer_id);
2090         ofm->out_port = htons(ofp_to_u16(fm->out_port));
2091         ofm->flags = raw_flags;
2092         ofpacts_put_openflow_actions(fm->ofpacts, fm->ofpacts_len, msg,
2093                                      version);
2094         break;
2095     }
2096
2097     case OFPUTIL_P_OF10_NXM:
2098     case OFPUTIL_P_OF10_NXM_TID: {
2099         struct nx_flow_mod *nfm;
2100         int match_len;
2101
2102         msg = ofpraw_alloc(OFPRAW_NXT_FLOW_MOD, OFP10_VERSION,
2103                            NXM_TYPICAL_LEN + fm->ofpacts_len);
2104         nfm = ofpbuf_put_zeros(msg, sizeof *nfm);
2105         nfm->command = ofputil_tid_command(fm, protocol);
2106         nfm->cookie = fm->new_cookie;
2107         match_len = nx_put_match(msg, &fm->match, fm->cookie, fm->cookie_mask);
2108         nfm = msg->l3;
2109         nfm->idle_timeout = htons(fm->idle_timeout);
2110         nfm->hard_timeout = htons(fm->hard_timeout);
2111         nfm->priority = htons(fm->priority);
2112         nfm->buffer_id = htonl(fm->buffer_id);
2113         nfm->out_port = htons(ofp_to_u16(fm->out_port));
2114         nfm->flags = raw_flags;
2115         nfm->match_len = htons(match_len);
2116         ofpacts_put_openflow_actions(fm->ofpacts, fm->ofpacts_len, msg,
2117                                      version);
2118         break;
2119     }
2120
2121     default:
2122         NOT_REACHED();
2123     }
2124
2125     ofpmsg_update_length(msg);
2126     return msg;
2127 }
2128
2129 static enum ofperr
2130 ofputil_decode_ofpst10_flow_request(struct ofputil_flow_stats_request *fsr,
2131                                     const struct ofp10_flow_stats_request *ofsr,
2132                                     bool aggregate)
2133 {
2134     fsr->aggregate = aggregate;
2135     ofputil_match_from_ofp10_match(&ofsr->match, &fsr->match);
2136     fsr->out_port = u16_to_ofp(ntohs(ofsr->out_port));
2137     fsr->out_group = OFPG11_ANY;
2138     fsr->table_id = ofsr->table_id;
2139     fsr->cookie = fsr->cookie_mask = htonll(0);
2140
2141     return 0;
2142 }
2143
2144 static enum ofperr
2145 ofputil_decode_ofpst11_flow_request(struct ofputil_flow_stats_request *fsr,
2146                                     struct ofpbuf *b, bool aggregate)
2147 {
2148     const struct ofp11_flow_stats_request *ofsr;
2149     enum ofperr error;
2150
2151     ofsr = ofpbuf_pull(b, sizeof *ofsr);
2152     fsr->aggregate = aggregate;
2153     fsr->table_id = ofsr->table_id;
2154     error = ofputil_port_from_ofp11(ofsr->out_port, &fsr->out_port);
2155     if (error) {
2156         return error;
2157     }
2158     fsr->out_group = ntohl(ofsr->out_group);
2159     fsr->cookie = ofsr->cookie;
2160     fsr->cookie_mask = ofsr->cookie_mask;
2161     error = ofputil_pull_ofp11_match(b, &fsr->match, NULL);
2162     if (error) {
2163         return error;
2164     }
2165
2166     return 0;
2167 }
2168
2169 static enum ofperr
2170 ofputil_decode_nxst_flow_request(struct ofputil_flow_stats_request *fsr,
2171                                  struct ofpbuf *b, bool aggregate)
2172 {
2173     const struct nx_flow_stats_request *nfsr;
2174     enum ofperr error;
2175
2176     nfsr = ofpbuf_pull(b, sizeof *nfsr);
2177     error = nx_pull_match(b, ntohs(nfsr->match_len), &fsr->match,
2178                           &fsr->cookie, &fsr->cookie_mask);
2179     if (error) {
2180         return error;
2181     }
2182     if (b->size) {
2183         return OFPERR_OFPBRC_BAD_LEN;
2184     }
2185
2186     fsr->aggregate = aggregate;
2187     fsr->out_port = u16_to_ofp(ntohs(nfsr->out_port));
2188     fsr->out_group = OFPG11_ANY;
2189     fsr->table_id = nfsr->table_id;
2190
2191     return 0;
2192 }
2193
2194 /* Constructs and returns an OFPT_QUEUE_GET_CONFIG request for the specified
2195  * 'port', suitable for OpenFlow version 'version'. */
2196 struct ofpbuf *
2197 ofputil_encode_queue_get_config_request(enum ofp_version version,
2198                                         ofp_port_t port)
2199 {
2200     struct ofpbuf *request;
2201
2202     if (version == OFP10_VERSION) {
2203         struct ofp10_queue_get_config_request *qgcr10;
2204
2205         request = ofpraw_alloc(OFPRAW_OFPT10_QUEUE_GET_CONFIG_REQUEST,
2206                                version, 0);
2207         qgcr10 = ofpbuf_put_zeros(request, sizeof *qgcr10);
2208         qgcr10->port = htons(ofp_to_u16(port));
2209     } else {
2210         struct ofp11_queue_get_config_request *qgcr11;
2211
2212         request = ofpraw_alloc(OFPRAW_OFPT11_QUEUE_GET_CONFIG_REQUEST,
2213                                version, 0);
2214         qgcr11 = ofpbuf_put_zeros(request, sizeof *qgcr11);
2215         qgcr11->port = ofputil_port_to_ofp11(port);
2216     }
2217
2218     return request;
2219 }
2220
2221 /* Parses OFPT_QUEUE_GET_CONFIG request 'oh', storing the port specified by the
2222  * request into '*port'.  Returns 0 if successful, otherwise an OpenFlow error
2223  * code. */
2224 enum ofperr
2225 ofputil_decode_queue_get_config_request(const struct ofp_header *oh,
2226                                         ofp_port_t *port)
2227 {
2228     const struct ofp10_queue_get_config_request *qgcr10;
2229     const struct ofp11_queue_get_config_request *qgcr11;
2230     enum ofpraw raw;
2231     struct ofpbuf b;
2232
2233     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2234     raw = ofpraw_pull_assert(&b);
2235
2236     switch ((int) raw) {
2237     case OFPRAW_OFPT10_QUEUE_GET_CONFIG_REQUEST:
2238         qgcr10 = b.data;
2239         *port = u16_to_ofp(ntohs(qgcr10->port));
2240         return 0;
2241
2242     case OFPRAW_OFPT11_QUEUE_GET_CONFIG_REQUEST:
2243         qgcr11 = b.data;
2244         return ofputil_port_from_ofp11(qgcr11->port, port);
2245     }
2246
2247     NOT_REACHED();
2248 }
2249
2250 /* Constructs and returns the beginning of a reply to
2251  * OFPT_QUEUE_GET_CONFIG_REQUEST 'oh'.  The caller may append information about
2252  * individual queues with ofputil_append_queue_get_config_reply(). */
2253 struct ofpbuf *
2254 ofputil_encode_queue_get_config_reply(const struct ofp_header *oh)
2255 {
2256     struct ofp10_queue_get_config_reply *qgcr10;
2257     struct ofp11_queue_get_config_reply *qgcr11;
2258     struct ofpbuf *reply;
2259     enum ofperr error;
2260     struct ofpbuf b;
2261     enum ofpraw raw;
2262     ofp_port_t port;
2263
2264     error = ofputil_decode_queue_get_config_request(oh, &port);
2265     ovs_assert(!error);
2266
2267     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2268     raw = ofpraw_pull_assert(&b);
2269
2270     switch ((int) raw) {
2271     case OFPRAW_OFPT10_QUEUE_GET_CONFIG_REQUEST:
2272         reply = ofpraw_alloc_reply(OFPRAW_OFPT10_QUEUE_GET_CONFIG_REPLY,
2273                                    oh, 0);
2274         qgcr10 = ofpbuf_put_zeros(reply, sizeof *qgcr10);
2275         qgcr10->port = htons(ofp_to_u16(port));
2276         break;
2277
2278     case OFPRAW_OFPT11_QUEUE_GET_CONFIG_REQUEST:
2279         reply = ofpraw_alloc_reply(OFPRAW_OFPT11_QUEUE_GET_CONFIG_REPLY,
2280                                    oh, 0);
2281         qgcr11 = ofpbuf_put_zeros(reply, sizeof *qgcr11);
2282         qgcr11->port = ofputil_port_to_ofp11(port);
2283         break;
2284
2285     default:
2286         NOT_REACHED();
2287     }
2288
2289     return reply;
2290 }
2291
2292 static void
2293 put_queue_rate(struct ofpbuf *reply, enum ofp_queue_properties property,
2294                uint16_t rate)
2295 {
2296     if (rate != UINT16_MAX) {
2297         struct ofp_queue_prop_rate *oqpr;
2298
2299         oqpr = ofpbuf_put_zeros(reply, sizeof *oqpr);
2300         oqpr->prop_header.property = htons(property);
2301         oqpr->prop_header.len = htons(sizeof *oqpr);
2302         oqpr->rate = htons(rate);
2303     }
2304 }
2305
2306 /* Appends a queue description for 'queue_id' to the
2307  * OFPT_QUEUE_GET_CONFIG_REPLY already in 'oh'. */
2308 void
2309 ofputil_append_queue_get_config_reply(struct ofpbuf *reply,
2310                                       const struct ofputil_queue_config *oqc)
2311 {
2312     const struct ofp_header *oh = reply->data;
2313     size_t start_ofs, len_ofs;
2314     ovs_be16 *len;
2315
2316     start_ofs = reply->size;
2317     if (oh->version < OFP12_VERSION) {
2318         struct ofp10_packet_queue *opq10;
2319
2320         opq10 = ofpbuf_put_zeros(reply, sizeof *opq10);
2321         opq10->queue_id = htonl(oqc->queue_id);
2322         len_ofs = (char *) &opq10->len - (char *) reply->data;
2323     } else {
2324         struct ofp11_queue_get_config_reply *qgcr11;
2325         struct ofp12_packet_queue *opq12;
2326         ovs_be32 port;
2327
2328         qgcr11 = reply->l3;
2329         port = qgcr11->port;
2330
2331         opq12 = ofpbuf_put_zeros(reply, sizeof *opq12);
2332         opq12->port = port;
2333         opq12->queue_id = htonl(oqc->queue_id);
2334         len_ofs = (char *) &opq12->len - (char *) reply->data;
2335     }
2336
2337     put_queue_rate(reply, OFPQT_MIN_RATE, oqc->min_rate);
2338     put_queue_rate(reply, OFPQT_MAX_RATE, oqc->max_rate);
2339
2340     len = ofpbuf_at(reply, len_ofs, sizeof *len);
2341     *len = htons(reply->size - start_ofs);
2342 }
2343
2344 /* Decodes the initial part of an OFPT_QUEUE_GET_CONFIG_REPLY from 'reply' and
2345  * stores in '*port' the port that the reply is about.  The caller may call
2346  * ofputil_pull_queue_get_config_reply() to obtain information about individual
2347  * queues included in the reply.  Returns 0 if successful, otherwise an
2348  * ofperr.*/
2349 enum ofperr
2350 ofputil_decode_queue_get_config_reply(struct ofpbuf *reply, ofp_port_t *port)
2351 {
2352     const struct ofp10_queue_get_config_reply *qgcr10;
2353     const struct ofp11_queue_get_config_reply *qgcr11;
2354     enum ofpraw raw;
2355
2356     raw = ofpraw_pull_assert(reply);
2357     switch ((int) raw) {
2358     case OFPRAW_OFPT10_QUEUE_GET_CONFIG_REPLY:
2359         qgcr10 = ofpbuf_pull(reply, sizeof *qgcr10);
2360         *port = u16_to_ofp(ntohs(qgcr10->port));
2361         return 0;
2362
2363     case OFPRAW_OFPT11_QUEUE_GET_CONFIG_REPLY:
2364         qgcr11 = ofpbuf_pull(reply, sizeof *qgcr11);
2365         return ofputil_port_from_ofp11(qgcr11->port, port);
2366     }
2367
2368     NOT_REACHED();
2369 }
2370
2371 static enum ofperr
2372 parse_queue_rate(const struct ofp_queue_prop_header *hdr, uint16_t *rate)
2373 {
2374     const struct ofp_queue_prop_rate *oqpr;
2375
2376     if (hdr->len == htons(sizeof *oqpr)) {
2377         oqpr = (const struct ofp_queue_prop_rate *) hdr;
2378         *rate = ntohs(oqpr->rate);
2379         return 0;
2380     } else {
2381         return OFPERR_OFPBRC_BAD_LEN;
2382     }
2383 }
2384
2385 /* Decodes information about a queue from the OFPT_QUEUE_GET_CONFIG_REPLY in
2386  * 'reply' and stores it in '*queue'.  ofputil_decode_queue_get_config_reply()
2387  * must already have pulled off the main header.
2388  *
2389  * This function returns EOF if the last queue has already been decoded, 0 if a
2390  * queue was successfully decoded into '*queue', or an ofperr if there was a
2391  * problem decoding 'reply'. */
2392 int
2393 ofputil_pull_queue_get_config_reply(struct ofpbuf *reply,
2394                                     struct ofputil_queue_config *queue)
2395 {
2396     const struct ofp_header *oh;
2397     unsigned int opq_len;
2398     unsigned int len;
2399
2400     if (!reply->size) {
2401         return EOF;
2402     }
2403
2404     queue->min_rate = UINT16_MAX;
2405     queue->max_rate = UINT16_MAX;
2406
2407     oh = reply->l2;
2408     if (oh->version < OFP12_VERSION) {
2409         const struct ofp10_packet_queue *opq10;
2410
2411         opq10 = ofpbuf_try_pull(reply, sizeof *opq10);
2412         if (!opq10) {
2413             return OFPERR_OFPBRC_BAD_LEN;
2414         }
2415         queue->queue_id = ntohl(opq10->queue_id);
2416         len = ntohs(opq10->len);
2417         opq_len = sizeof *opq10;
2418     } else {
2419         const struct ofp12_packet_queue *opq12;
2420
2421         opq12 = ofpbuf_try_pull(reply, sizeof *opq12);
2422         if (!opq12) {
2423             return OFPERR_OFPBRC_BAD_LEN;
2424         }
2425         queue->queue_id = ntohl(opq12->queue_id);
2426         len = ntohs(opq12->len);
2427         opq_len = sizeof *opq12;
2428     }
2429
2430     if (len < opq_len || len > reply->size + opq_len || len % 8) {
2431         return OFPERR_OFPBRC_BAD_LEN;
2432     }
2433     len -= opq_len;
2434
2435     while (len > 0) {
2436         const struct ofp_queue_prop_header *hdr;
2437         unsigned int property;
2438         unsigned int prop_len;
2439         enum ofperr error = 0;
2440
2441         hdr = ofpbuf_at_assert(reply, 0, sizeof *hdr);
2442         prop_len = ntohs(hdr->len);
2443         if (prop_len < sizeof *hdr || prop_len > reply->size || prop_len % 8) {
2444             return OFPERR_OFPBRC_BAD_LEN;
2445         }
2446
2447         property = ntohs(hdr->property);
2448         switch (property) {
2449         case OFPQT_MIN_RATE:
2450             error = parse_queue_rate(hdr, &queue->min_rate);
2451             break;
2452
2453         case OFPQT_MAX_RATE:
2454             error = parse_queue_rate(hdr, &queue->max_rate);
2455             break;
2456
2457         default:
2458             VLOG_INFO_RL(&bad_ofmsg_rl, "unknown queue property %u", property);
2459             break;
2460         }
2461         if (error) {
2462             return error;
2463         }
2464
2465         ofpbuf_pull(reply, prop_len);
2466         len -= prop_len;
2467     }
2468     return 0;
2469 }
2470
2471 /* Converts an OFPST_FLOW, OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE
2472  * request 'oh', into an abstract flow_stats_request in 'fsr'.  Returns 0 if
2473  * successful, otherwise an OpenFlow error code. */
2474 enum ofperr
2475 ofputil_decode_flow_stats_request(struct ofputil_flow_stats_request *fsr,
2476                                   const struct ofp_header *oh)
2477 {
2478     enum ofpraw raw;
2479     struct ofpbuf b;
2480
2481     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2482     raw = ofpraw_pull_assert(&b);
2483     switch ((int) raw) {
2484     case OFPRAW_OFPST10_FLOW_REQUEST:
2485         return ofputil_decode_ofpst10_flow_request(fsr, b.data, false);
2486
2487     case OFPRAW_OFPST10_AGGREGATE_REQUEST:
2488         return ofputil_decode_ofpst10_flow_request(fsr, b.data, true);
2489
2490     case OFPRAW_OFPST11_FLOW_REQUEST:
2491         return ofputil_decode_ofpst11_flow_request(fsr, &b, false);
2492
2493     case OFPRAW_OFPST11_AGGREGATE_REQUEST:
2494         return ofputil_decode_ofpst11_flow_request(fsr, &b, true);
2495
2496     case OFPRAW_NXST_FLOW_REQUEST:
2497         return ofputil_decode_nxst_flow_request(fsr, &b, false);
2498
2499     case OFPRAW_NXST_AGGREGATE_REQUEST:
2500         return ofputil_decode_nxst_flow_request(fsr, &b, true);
2501
2502     default:
2503         /* Hey, the caller lied. */
2504         NOT_REACHED();
2505     }
2506 }
2507
2508 /* Converts abstract flow_stats_request 'fsr' into an OFPST_FLOW,
2509  * OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE request 'oh' according to
2510  * 'protocol', and returns the message. */
2511 struct ofpbuf *
2512 ofputil_encode_flow_stats_request(const struct ofputil_flow_stats_request *fsr,
2513                                   enum ofputil_protocol protocol)
2514 {
2515     struct ofpbuf *msg;
2516     enum ofpraw raw;
2517
2518     switch (protocol) {
2519     case OFPUTIL_P_OF11_STD:
2520     case OFPUTIL_P_OF12_OXM:
2521     case OFPUTIL_P_OF13_OXM: {
2522         struct ofp11_flow_stats_request *ofsr;
2523
2524         raw = (fsr->aggregate
2525                ? OFPRAW_OFPST11_AGGREGATE_REQUEST
2526                : OFPRAW_OFPST11_FLOW_REQUEST);
2527         msg = ofpraw_alloc(raw, ofputil_protocol_to_ofp_version(protocol),
2528                            ofputil_match_typical_len(protocol));
2529         ofsr = ofpbuf_put_zeros(msg, sizeof *ofsr);
2530         ofsr->table_id = fsr->table_id;
2531         ofsr->out_port = ofputil_port_to_ofp11(fsr->out_port);
2532         ofsr->out_group = htonl(fsr->out_group);
2533         ofsr->cookie = fsr->cookie;
2534         ofsr->cookie_mask = fsr->cookie_mask;
2535         ofputil_put_ofp11_match(msg, &fsr->match, protocol);
2536         break;
2537     }
2538
2539     case OFPUTIL_P_OF10_STD:
2540     case OFPUTIL_P_OF10_STD_TID: {
2541         struct ofp10_flow_stats_request *ofsr;
2542
2543         raw = (fsr->aggregate
2544                ? OFPRAW_OFPST10_AGGREGATE_REQUEST
2545                : OFPRAW_OFPST10_FLOW_REQUEST);
2546         msg = ofpraw_alloc(raw, OFP10_VERSION, 0);
2547         ofsr = ofpbuf_put_zeros(msg, sizeof *ofsr);
2548         ofputil_match_to_ofp10_match(&fsr->match, &ofsr->match);
2549         ofsr->table_id = fsr->table_id;
2550         ofsr->out_port = htons(ofp_to_u16(fsr->out_port));
2551         break;
2552     }
2553
2554     case OFPUTIL_P_OF10_NXM:
2555     case OFPUTIL_P_OF10_NXM_TID: {
2556         struct nx_flow_stats_request *nfsr;
2557         int match_len;
2558
2559         raw = (fsr->aggregate
2560                ? OFPRAW_NXST_AGGREGATE_REQUEST
2561                : OFPRAW_NXST_FLOW_REQUEST);
2562         msg = ofpraw_alloc(raw, OFP10_VERSION, NXM_TYPICAL_LEN);
2563         ofpbuf_put_zeros(msg, sizeof *nfsr);
2564         match_len = nx_put_match(msg, &fsr->match,
2565                                  fsr->cookie, fsr->cookie_mask);
2566
2567         nfsr = msg->l3;
2568         nfsr->out_port = htons(ofp_to_u16(fsr->out_port));
2569         nfsr->match_len = htons(match_len);
2570         nfsr->table_id = fsr->table_id;
2571         break;
2572     }
2573
2574     default:
2575         NOT_REACHED();
2576     }
2577
2578     return msg;
2579 }
2580
2581 /* Converts an OFPST_FLOW or NXST_FLOW reply in 'msg' into an abstract
2582  * ofputil_flow_stats in 'fs'.
2583  *
2584  * Multiple OFPST_FLOW or NXST_FLOW replies can be packed into a single
2585  * OpenFlow message.  Calling this function multiple times for a single 'msg'
2586  * iterates through the replies.  The caller must initially leave 'msg''s layer
2587  * pointers null and not modify them between calls.
2588  *
2589  * Most switches don't send the values needed to populate fs->idle_age and
2590  * fs->hard_age, so those members will usually be set to 0.  If the switch from
2591  * which 'msg' originated is known to implement NXT_FLOW_AGE, then pass
2592  * 'flow_age_extension' as true so that the contents of 'msg' determine the
2593  * 'idle_age' and 'hard_age' members in 'fs'.
2594  *
2595  * Uses 'ofpacts' to store the abstract OFPACT_* version of the flow stats
2596  * reply's actions.  The caller must initialize 'ofpacts' and retains ownership
2597  * of it.  'fs->ofpacts' will point into the 'ofpacts' buffer.
2598  *
2599  * Returns 0 if successful, EOF if no replies were left in this 'msg',
2600  * otherwise a positive errno value. */
2601 int
2602 ofputil_decode_flow_stats_reply(struct ofputil_flow_stats *fs,
2603                                 struct ofpbuf *msg,
2604                                 bool flow_age_extension,
2605                                 struct ofpbuf *ofpacts)
2606 {
2607     const struct ofp_header *oh;
2608     enum ofperr error;
2609     enum ofpraw raw;
2610
2611     error = (msg->l2
2612              ? ofpraw_decode(&raw, msg->l2)
2613              : ofpraw_pull(&raw, msg));
2614     if (error) {
2615         return error;
2616     }
2617     oh = msg->l2;
2618
2619     if (!msg->size) {
2620         return EOF;
2621     } else if (raw == OFPRAW_OFPST11_FLOW_REPLY
2622                || raw == OFPRAW_OFPST13_FLOW_REPLY) {
2623         const struct ofp11_flow_stats *ofs;
2624         size_t length;
2625         uint16_t padded_match_len;
2626
2627         ofs = ofpbuf_try_pull(msg, sizeof *ofs);
2628         if (!ofs) {
2629             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply has %zu leftover "
2630                          "bytes at end", msg->size);
2631             return EINVAL;
2632         }
2633
2634         length = ntohs(ofs->length);
2635         if (length < sizeof *ofs) {
2636             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply claims invalid "
2637                          "length %zu", length);
2638             return EINVAL;
2639         }
2640
2641         if (ofputil_pull_ofp11_match(msg, &fs->match, &padded_match_len)) {
2642             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply bad match");
2643             return EINVAL;
2644         }
2645
2646         if (ofpacts_pull_openflow_instructions(msg, length - sizeof *ofs -
2647                                                padded_match_len, oh->version,
2648                                                ofpacts)) {
2649             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply bad instructions");
2650             return EINVAL;
2651         }
2652
2653         fs->priority = ntohs(ofs->priority);
2654         fs->table_id = ofs->table_id;
2655         fs->duration_sec = ntohl(ofs->duration_sec);
2656         fs->duration_nsec = ntohl(ofs->duration_nsec);
2657         fs->idle_timeout = ntohs(ofs->idle_timeout);
2658         fs->hard_timeout = ntohs(ofs->hard_timeout);
2659         if (raw == OFPRAW_OFPST13_FLOW_REPLY) {
2660             error = ofputil_decode_flow_mod_flags(ofs->flags, -1, oh->version,
2661                                                   &fs->flags);
2662             if (error) {
2663                 return error;
2664             }
2665         } else {
2666             fs->flags = 0;
2667         }
2668         fs->idle_age = -1;
2669         fs->hard_age = -1;
2670         fs->cookie = ofs->cookie;
2671         fs->packet_count = ntohll(ofs->packet_count);
2672         fs->byte_count = ntohll(ofs->byte_count);
2673     } else if (raw == OFPRAW_OFPST10_FLOW_REPLY) {
2674         const struct ofp10_flow_stats *ofs;
2675         size_t length;
2676
2677         ofs = ofpbuf_try_pull(msg, sizeof *ofs);
2678         if (!ofs) {
2679             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply has %zu leftover "
2680                          "bytes at end", msg->size);
2681             return EINVAL;
2682         }
2683
2684         length = ntohs(ofs->length);
2685         if (length < sizeof *ofs) {
2686             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply claims invalid "
2687                          "length %zu", length);
2688             return EINVAL;
2689         }
2690
2691         if (ofpacts_pull_openflow_actions(msg, length - sizeof *ofs,
2692                                           oh->version, ofpacts)) {
2693             return EINVAL;
2694         }
2695
2696         fs->cookie = get_32aligned_be64(&ofs->cookie);
2697         ofputil_match_from_ofp10_match(&ofs->match, &fs->match);
2698         fs->priority = ntohs(ofs->priority);
2699         fs->table_id = ofs->table_id;
2700         fs->duration_sec = ntohl(ofs->duration_sec);
2701         fs->duration_nsec = ntohl(ofs->duration_nsec);
2702         fs->idle_timeout = ntohs(ofs->idle_timeout);
2703         fs->hard_timeout = ntohs(ofs->hard_timeout);
2704         fs->idle_age = -1;
2705         fs->hard_age = -1;
2706         fs->packet_count = ntohll(get_32aligned_be64(&ofs->packet_count));
2707         fs->byte_count = ntohll(get_32aligned_be64(&ofs->byte_count));
2708         fs->flags = 0;
2709     } else if (raw == OFPRAW_NXST_FLOW_REPLY) {
2710         const struct nx_flow_stats *nfs;
2711         size_t match_len, actions_len, length;
2712
2713         nfs = ofpbuf_try_pull(msg, sizeof *nfs);
2714         if (!nfs) {
2715             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply has %zu leftover "
2716                          "bytes at end", msg->size);
2717             return EINVAL;
2718         }
2719
2720         length = ntohs(nfs->length);
2721         match_len = ntohs(nfs->match_len);
2722         if (length < sizeof *nfs + ROUND_UP(match_len, 8)) {
2723             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply with match_len=%zu "
2724                          "claims invalid length %zu", match_len, length);
2725             return EINVAL;
2726         }
2727         if (nx_pull_match(msg, match_len, &fs->match, NULL, NULL)) {
2728             return EINVAL;
2729         }
2730
2731         actions_len = length - sizeof *nfs - ROUND_UP(match_len, 8);
2732         if (ofpacts_pull_openflow_actions(msg, actions_len, oh->version,
2733                                           ofpacts)) {
2734             return EINVAL;
2735         }
2736
2737         fs->cookie = nfs->cookie;
2738         fs->table_id = nfs->table_id;
2739         fs->duration_sec = ntohl(nfs->duration_sec);
2740         fs->duration_nsec = ntohl(nfs->duration_nsec);
2741         fs->priority = ntohs(nfs->priority);
2742         fs->idle_timeout = ntohs(nfs->idle_timeout);
2743         fs->hard_timeout = ntohs(nfs->hard_timeout);
2744         fs->idle_age = -1;
2745         fs->hard_age = -1;
2746         if (flow_age_extension) {
2747             if (nfs->idle_age) {
2748                 fs->idle_age = ntohs(nfs->idle_age) - 1;
2749             }
2750             if (nfs->hard_age) {
2751                 fs->hard_age = ntohs(nfs->hard_age) - 1;
2752             }
2753         }
2754         fs->packet_count = ntohll(nfs->packet_count);
2755         fs->byte_count = ntohll(nfs->byte_count);
2756         fs->flags = 0;
2757     } else {
2758         NOT_REACHED();
2759     }
2760
2761     fs->ofpacts = ofpacts->data;
2762     fs->ofpacts_len = ofpacts->size;
2763
2764     return 0;
2765 }
2766
2767 /* Returns 'count' unchanged except that UINT64_MAX becomes 0.
2768  *
2769  * We use this in situations where OVS internally uses UINT64_MAX to mean
2770  * "value unknown" but OpenFlow 1.0 does not define any unknown value. */
2771 static uint64_t
2772 unknown_to_zero(uint64_t count)
2773 {
2774     return count != UINT64_MAX ? count : 0;
2775 }
2776
2777 /* Appends an OFPST_FLOW or NXST_FLOW reply that contains the data in 'fs' to
2778  * those already present in the list of ofpbufs in 'replies'.  'replies' should
2779  * have been initialized with ofpmp_init(). */
2780 void
2781 ofputil_append_flow_stats_reply(const struct ofputil_flow_stats *fs,
2782                                 struct list *replies)
2783 {
2784     struct ofpbuf *reply = ofpbuf_from_list(list_back(replies));
2785     size_t start_ofs = reply->size;
2786     enum ofpraw raw;
2787     enum ofp_version version = ((struct ofp_header *)reply->data)->version;
2788
2789     ofpraw_decode_partial(&raw, reply->data, reply->size);
2790     if (raw == OFPRAW_OFPST11_FLOW_REPLY || raw == OFPRAW_OFPST13_FLOW_REPLY) {
2791         struct ofp11_flow_stats *ofs;
2792
2793         ofpbuf_put_uninit(reply, sizeof *ofs);
2794         oxm_put_match(reply, &fs->match);
2795         ofpacts_put_openflow_instructions(fs->ofpacts, fs->ofpacts_len, reply,
2796                                           version);
2797
2798         ofs = ofpbuf_at_assert(reply, start_ofs, sizeof *ofs);
2799         ofs->length = htons(reply->size - start_ofs);
2800         ofs->table_id = fs->table_id;
2801         ofs->pad = 0;
2802         ofs->duration_sec = htonl(fs->duration_sec);
2803         ofs->duration_nsec = htonl(fs->duration_nsec);
2804         ofs->priority = htons(fs->priority);
2805         ofs->idle_timeout = htons(fs->idle_timeout);
2806         ofs->hard_timeout = htons(fs->hard_timeout);
2807         if (raw == OFPRAW_OFPST13_FLOW_REPLY) {
2808             ofs->flags = ofputil_encode_flow_mod_flags(fs->flags, version);
2809         } else {
2810             ofs->flags = 0;
2811         }
2812         memset(ofs->pad2, 0, sizeof ofs->pad2);
2813         ofs->cookie = fs->cookie;
2814         ofs->packet_count = htonll(unknown_to_zero(fs->packet_count));
2815         ofs->byte_count = htonll(unknown_to_zero(fs->byte_count));
2816     } else if (raw == OFPRAW_OFPST10_FLOW_REPLY) {
2817         struct ofp10_flow_stats *ofs;
2818
2819         ofpbuf_put_uninit(reply, sizeof *ofs);
2820         ofpacts_put_openflow_actions(fs->ofpacts, fs->ofpacts_len, reply,
2821                                      version);
2822         ofs = ofpbuf_at_assert(reply, start_ofs, sizeof *ofs);
2823         ofs->length = htons(reply->size - start_ofs);
2824         ofs->table_id = fs->table_id;
2825         ofs->pad = 0;
2826         ofputil_match_to_ofp10_match(&fs->match, &ofs->match);
2827         ofs->duration_sec = htonl(fs->duration_sec);
2828         ofs->duration_nsec = htonl(fs->duration_nsec);
2829         ofs->priority = htons(fs->priority);
2830         ofs->idle_timeout = htons(fs->idle_timeout);
2831         ofs->hard_timeout = htons(fs->hard_timeout);
2832         memset(ofs->pad2, 0, sizeof ofs->pad2);
2833         put_32aligned_be64(&ofs->cookie, fs->cookie);
2834         put_32aligned_be64(&ofs->packet_count,
2835                            htonll(unknown_to_zero(fs->packet_count)));
2836         put_32aligned_be64(&ofs->byte_count,
2837                            htonll(unknown_to_zero(fs->byte_count)));
2838     } else if (raw == OFPRAW_NXST_FLOW_REPLY) {
2839         struct nx_flow_stats *nfs;
2840         int match_len;
2841
2842         ofpbuf_put_uninit(reply, sizeof *nfs);
2843         match_len = nx_put_match(reply, &fs->match, 0, 0);
2844         ofpacts_put_openflow_actions(fs->ofpacts, fs->ofpacts_len, reply,
2845                                      version);
2846         nfs = ofpbuf_at_assert(reply, start_ofs, sizeof *nfs);
2847         nfs->length = htons(reply->size - start_ofs);
2848         nfs->table_id = fs->table_id;
2849         nfs->pad = 0;
2850         nfs->duration_sec = htonl(fs->duration_sec);
2851         nfs->duration_nsec = htonl(fs->duration_nsec);
2852         nfs->priority = htons(fs->priority);
2853         nfs->idle_timeout = htons(fs->idle_timeout);
2854         nfs->hard_timeout = htons(fs->hard_timeout);
2855         nfs->idle_age = htons(fs->idle_age < 0 ? 0
2856                               : fs->idle_age < UINT16_MAX ? fs->idle_age + 1
2857                               : UINT16_MAX);
2858         nfs->hard_age = htons(fs->hard_age < 0 ? 0
2859                               : fs->hard_age < UINT16_MAX ? fs->hard_age + 1
2860                               : UINT16_MAX);
2861         nfs->match_len = htons(match_len);
2862         nfs->cookie = fs->cookie;
2863         nfs->packet_count = htonll(fs->packet_count);
2864         nfs->byte_count = htonll(fs->byte_count);
2865     } else {
2866         NOT_REACHED();
2867     }
2868
2869     ofpmp_postappend(replies, start_ofs);
2870 }
2871
2872 /* Converts abstract ofputil_aggregate_stats 'stats' into an OFPST_AGGREGATE or
2873  * NXST_AGGREGATE reply matching 'request', and returns the message. */
2874 struct ofpbuf *
2875 ofputil_encode_aggregate_stats_reply(
2876     const struct ofputil_aggregate_stats *stats,
2877     const struct ofp_header *request)
2878 {
2879     struct ofp_aggregate_stats_reply *asr;
2880     uint64_t packet_count;
2881     uint64_t byte_count;
2882     struct ofpbuf *msg;
2883     enum ofpraw raw;
2884
2885     ofpraw_decode(&raw, request);
2886     if (raw == OFPRAW_OFPST10_AGGREGATE_REQUEST) {
2887         packet_count = unknown_to_zero(stats->packet_count);
2888         byte_count = unknown_to_zero(stats->byte_count);
2889     } else {
2890         packet_count = stats->packet_count;
2891         byte_count = stats->byte_count;
2892     }
2893
2894     msg = ofpraw_alloc_stats_reply(request, 0);
2895     asr = ofpbuf_put_zeros(msg, sizeof *asr);
2896     put_32aligned_be64(&asr->packet_count, htonll(packet_count));
2897     put_32aligned_be64(&asr->byte_count, htonll(byte_count));
2898     asr->flow_count = htonl(stats->flow_count);
2899
2900     return msg;
2901 }
2902
2903 enum ofperr
2904 ofputil_decode_aggregate_stats_reply(struct ofputil_aggregate_stats *stats,
2905                                      const struct ofp_header *reply)
2906 {
2907     struct ofp_aggregate_stats_reply *asr;
2908     struct ofpbuf msg;
2909
2910     ofpbuf_use_const(&msg, reply, ntohs(reply->length));
2911     ofpraw_pull_assert(&msg);
2912
2913     asr = msg.l3;
2914     stats->packet_count = ntohll(get_32aligned_be64(&asr->packet_count));
2915     stats->byte_count = ntohll(get_32aligned_be64(&asr->byte_count));
2916     stats->flow_count = ntohl(asr->flow_count);
2917
2918     return 0;
2919 }
2920
2921 /* Converts an OFPT_FLOW_REMOVED or NXT_FLOW_REMOVED message 'oh' into an
2922  * abstract ofputil_flow_removed in 'fr'.  Returns 0 if successful, otherwise
2923  * an OpenFlow error code. */
2924 enum ofperr
2925 ofputil_decode_flow_removed(struct ofputil_flow_removed *fr,
2926                             const struct ofp_header *oh)
2927 {
2928     enum ofpraw raw;
2929     struct ofpbuf b;
2930
2931     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2932     raw = ofpraw_pull_assert(&b);
2933     if (raw == OFPRAW_OFPT11_FLOW_REMOVED) {
2934         const struct ofp12_flow_removed *ofr;
2935         enum ofperr error;
2936
2937         ofr = ofpbuf_pull(&b, sizeof *ofr);
2938
2939         error = ofputil_pull_ofp11_match(&b, &fr->match, NULL);
2940         if (error) {
2941             return error;
2942         }
2943
2944         fr->priority = ntohs(ofr->priority);
2945         fr->cookie = ofr->cookie;
2946         fr->reason = ofr->reason;
2947         fr->table_id = ofr->table_id;
2948         fr->duration_sec = ntohl(ofr->duration_sec);
2949         fr->duration_nsec = ntohl(ofr->duration_nsec);
2950         fr->idle_timeout = ntohs(ofr->idle_timeout);
2951         fr->hard_timeout = ntohs(ofr->hard_timeout);
2952         fr->packet_count = ntohll(ofr->packet_count);
2953         fr->byte_count = ntohll(ofr->byte_count);
2954     } else if (raw == OFPRAW_OFPT10_FLOW_REMOVED) {
2955         const struct ofp10_flow_removed *ofr;
2956
2957         ofr = ofpbuf_pull(&b, sizeof *ofr);
2958
2959         ofputil_match_from_ofp10_match(&ofr->match, &fr->match);
2960         fr->priority = ntohs(ofr->priority);
2961         fr->cookie = ofr->cookie;
2962         fr->reason = ofr->reason;
2963         fr->table_id = 255;
2964         fr->duration_sec = ntohl(ofr->duration_sec);
2965         fr->duration_nsec = ntohl(ofr->duration_nsec);
2966         fr->idle_timeout = ntohs(ofr->idle_timeout);
2967         fr->hard_timeout = 0;
2968         fr->packet_count = ntohll(ofr->packet_count);
2969         fr->byte_count = ntohll(ofr->byte_count);
2970     } else if (raw == OFPRAW_NXT_FLOW_REMOVED) {
2971         struct nx_flow_removed *nfr;
2972         enum ofperr error;
2973
2974         nfr = ofpbuf_pull(&b, sizeof *nfr);
2975         error = nx_pull_match(&b, ntohs(nfr->match_len), &fr->match,
2976                               NULL, NULL);
2977         if (error) {
2978             return error;
2979         }
2980         if (b.size) {
2981             return OFPERR_OFPBRC_BAD_LEN;
2982         }
2983
2984         fr->priority = ntohs(nfr->priority);
2985         fr->cookie = nfr->cookie;
2986         fr->reason = nfr->reason;
2987         fr->table_id = nfr->table_id ? nfr->table_id - 1 : 255;
2988         fr->duration_sec = ntohl(nfr->duration_sec);
2989         fr->duration_nsec = ntohl(nfr->duration_nsec);
2990         fr->idle_timeout = ntohs(nfr->idle_timeout);
2991         fr->hard_timeout = 0;
2992         fr->packet_count = ntohll(nfr->packet_count);
2993         fr->byte_count = ntohll(nfr->byte_count);
2994     } else {
2995         NOT_REACHED();
2996     }
2997
2998     return 0;
2999 }
3000
3001 /* Converts abstract ofputil_flow_removed 'fr' into an OFPT_FLOW_REMOVED or
3002  * NXT_FLOW_REMOVED message 'oh' according to 'protocol', and returns the
3003  * message. */
3004 struct ofpbuf *
3005 ofputil_encode_flow_removed(const struct ofputil_flow_removed *fr,
3006                             enum ofputil_protocol protocol)
3007 {
3008     struct ofpbuf *msg;
3009
3010     switch (protocol) {
3011     case OFPUTIL_P_OF11_STD:
3012     case OFPUTIL_P_OF12_OXM:
3013     case OFPUTIL_P_OF13_OXM: {
3014         struct ofp12_flow_removed *ofr;
3015
3016         msg = ofpraw_alloc_xid(OFPRAW_OFPT11_FLOW_REMOVED,
3017                                ofputil_protocol_to_ofp_version(protocol),
3018                                htonl(0),
3019                                ofputil_match_typical_len(protocol));
3020         ofr = ofpbuf_put_zeros(msg, sizeof *ofr);
3021         ofr->cookie = fr->cookie;
3022         ofr->priority = htons(fr->priority);
3023         ofr->reason = fr->reason;
3024         ofr->table_id = fr->table_id;
3025         ofr->duration_sec = htonl(fr->duration_sec);
3026         ofr->duration_nsec = htonl(fr->duration_nsec);
3027         ofr->idle_timeout = htons(fr->idle_timeout);
3028         ofr->hard_timeout = htons(fr->hard_timeout);
3029         ofr->packet_count = htonll(fr->packet_count);
3030         ofr->byte_count = htonll(fr->byte_count);
3031         ofputil_put_ofp11_match(msg, &fr->match, protocol);
3032         break;
3033     }
3034
3035     case OFPUTIL_P_OF10_STD:
3036     case OFPUTIL_P_OF10_STD_TID: {
3037         struct ofp10_flow_removed *ofr;
3038
3039         msg = ofpraw_alloc_xid(OFPRAW_OFPT10_FLOW_REMOVED, OFP10_VERSION,
3040                                htonl(0), 0);
3041         ofr = ofpbuf_put_zeros(msg, sizeof *ofr);
3042         ofputil_match_to_ofp10_match(&fr->match, &ofr->match);
3043         ofr->cookie = fr->cookie;
3044         ofr->priority = htons(fr->priority);
3045         ofr->reason = fr->reason;
3046         ofr->duration_sec = htonl(fr->duration_sec);
3047         ofr->duration_nsec = htonl(fr->duration_nsec);
3048         ofr->idle_timeout = htons(fr->idle_timeout);
3049         ofr->packet_count = htonll(unknown_to_zero(fr->packet_count));
3050         ofr->byte_count = htonll(unknown_to_zero(fr->byte_count));
3051         break;
3052     }
3053
3054     case OFPUTIL_P_OF10_NXM:
3055     case OFPUTIL_P_OF10_NXM_TID: {
3056         struct nx_flow_removed *nfr;
3057         int match_len;
3058
3059         msg = ofpraw_alloc_xid(OFPRAW_NXT_FLOW_REMOVED, OFP10_VERSION,
3060                                htonl(0), NXM_TYPICAL_LEN);
3061         nfr = ofpbuf_put_zeros(msg, sizeof *nfr);
3062         match_len = nx_put_match(msg, &fr->match, 0, 0);
3063
3064         nfr = msg->l3;
3065         nfr->cookie = fr->cookie;
3066         nfr->priority = htons(fr->priority);
3067         nfr->reason = fr->reason;
3068         nfr->table_id = fr->table_id + 1;
3069         nfr->duration_sec = htonl(fr->duration_sec);
3070         nfr->duration_nsec = htonl(fr->duration_nsec);
3071         nfr->idle_timeout = htons(fr->idle_timeout);
3072         nfr->match_len = htons(match_len);
3073         nfr->packet_count = htonll(fr->packet_count);
3074         nfr->byte_count = htonll(fr->byte_count);
3075         break;
3076     }
3077
3078     default:
3079         NOT_REACHED();
3080     }
3081
3082     return msg;
3083 }
3084
3085 static void
3086 ofputil_decode_packet_in_finish(struct ofputil_packet_in *pin,
3087                                 struct match *match, struct ofpbuf *b)
3088 {
3089     pin->packet = b->data;
3090     pin->packet_len = b->size;
3091
3092     pin->fmd.in_port = match->flow.in_port.ofp_port;
3093     pin->fmd.tun_id = match->flow.tunnel.tun_id;
3094     pin->fmd.tun_src = match->flow.tunnel.ip_src;
3095     pin->fmd.tun_dst = match->flow.tunnel.ip_dst;
3096     pin->fmd.metadata = match->flow.metadata;
3097     memcpy(pin->fmd.regs, match->flow.regs, sizeof pin->fmd.regs);
3098     pin->fmd.pkt_mark = match->flow.pkt_mark;
3099 }
3100
3101 enum ofperr
3102 ofputil_decode_packet_in(struct ofputil_packet_in *pin,
3103                          const struct ofp_header *oh)
3104 {
3105     enum ofpraw raw;
3106     struct ofpbuf b;
3107
3108     memset(pin, 0, sizeof *pin);
3109     pin->cookie = OVS_BE64_MAX;
3110
3111     ofpbuf_use_const(&b, oh, ntohs(oh->length));
3112     raw = ofpraw_pull_assert(&b);
3113     if (raw == OFPRAW_OFPT13_PACKET_IN || raw == OFPRAW_OFPT12_PACKET_IN) {
3114         const struct ofp13_packet_in *opi;
3115         struct match match;
3116         int error;
3117         size_t packet_in_size;
3118
3119         if (raw == OFPRAW_OFPT12_PACKET_IN) {
3120             packet_in_size = sizeof (struct ofp12_packet_in);
3121         } else {
3122             packet_in_size = sizeof (struct ofp13_packet_in);
3123         }
3124
3125         opi = ofpbuf_pull(&b, packet_in_size);
3126         error = oxm_pull_match_loose(&b, &match);
3127         if (error) {
3128             return error;
3129         }
3130
3131         if (!ofpbuf_try_pull(&b, 2)) {
3132             return OFPERR_OFPBRC_BAD_LEN;
3133         }
3134
3135         pin->reason = opi->pi.reason;
3136         pin->table_id = opi->pi.table_id;
3137         pin->buffer_id = ntohl(opi->pi.buffer_id);
3138         pin->total_len = ntohs(opi->pi.total_len);
3139
3140         if (raw == OFPRAW_OFPT13_PACKET_IN) {
3141             pin->cookie = opi->cookie;
3142         }
3143
3144         ofputil_decode_packet_in_finish(pin, &match, &b);
3145     } else if (raw == OFPRAW_OFPT10_PACKET_IN) {
3146         const struct ofp10_packet_in *opi;
3147
3148         opi = ofpbuf_pull(&b, offsetof(struct ofp10_packet_in, data));
3149
3150         pin->packet = opi->data;
3151         pin->packet_len = b.size;
3152
3153         pin->fmd.in_port = u16_to_ofp(ntohs(opi->in_port));
3154         pin->reason = opi->reason;
3155         pin->buffer_id = ntohl(opi->buffer_id);
3156         pin->total_len = ntohs(opi->total_len);
3157     } else if (raw == OFPRAW_NXT_PACKET_IN) {
3158         const struct nx_packet_in *npi;
3159         struct match match;
3160         int error;
3161
3162         npi = ofpbuf_pull(&b, sizeof *npi);
3163         error = nx_pull_match_loose(&b, ntohs(npi->match_len), &match, NULL,
3164                                     NULL);
3165         if (error) {
3166             return error;
3167         }
3168
3169         if (!ofpbuf_try_pull(&b, 2)) {
3170             return OFPERR_OFPBRC_BAD_LEN;
3171         }
3172
3173         pin->reason = npi->reason;
3174         pin->table_id = npi->table_id;
3175         pin->cookie = npi->cookie;
3176
3177         pin->buffer_id = ntohl(npi->buffer_id);
3178         pin->total_len = ntohs(npi->total_len);
3179
3180         ofputil_decode_packet_in_finish(pin, &match, &b);
3181     } else {
3182         NOT_REACHED();
3183     }
3184
3185     return 0;
3186 }
3187
3188 static void
3189 ofputil_packet_in_to_match(const struct ofputil_packet_in *pin,
3190                            struct match *match)
3191 {
3192     int i;
3193
3194     match_init_catchall(match);
3195     if (pin->fmd.tun_id != htonll(0)) {
3196         match_set_tun_id(match, pin->fmd.tun_id);
3197     }
3198     if (pin->fmd.tun_src != htonl(0)) {
3199         match_set_tun_src(match, pin->fmd.tun_src);
3200     }
3201     if (pin->fmd.tun_dst != htonl(0)) {
3202         match_set_tun_dst(match, pin->fmd.tun_dst);
3203     }
3204     if (pin->fmd.metadata != htonll(0)) {
3205         match_set_metadata(match, pin->fmd.metadata);
3206     }
3207
3208     for (i = 0; i < FLOW_N_REGS; i++) {
3209         if (pin->fmd.regs[i]) {
3210             match_set_reg(match, i, pin->fmd.regs[i]);
3211         }
3212     }
3213
3214     if (pin->fmd.pkt_mark != 0) {
3215         match_set_pkt_mark(match, pin->fmd.pkt_mark);
3216     }
3217
3218     match_set_in_port(match, pin->fmd.in_port);
3219 }
3220
3221 /* Converts abstract ofputil_packet_in 'pin' into a PACKET_IN message
3222  * in the format specified by 'packet_in_format'.  */
3223 struct ofpbuf *
3224 ofputil_encode_packet_in(const struct ofputil_packet_in *pin,
3225                          enum ofputil_protocol protocol,
3226                          enum nx_packet_in_format packet_in_format)
3227 {
3228     struct ofpbuf *packet;
3229
3230     /* Add OFPT_PACKET_IN. */
3231     if (protocol == OFPUTIL_P_OF13_OXM || protocol == OFPUTIL_P_OF12_OXM) {
3232         struct ofp13_packet_in *opi;
3233         struct match match;
3234         enum ofpraw packet_in_raw;
3235         enum ofp_version packet_in_version;
3236         size_t packet_in_size;
3237
3238         if (protocol == OFPUTIL_P_OF12_OXM) {
3239             packet_in_raw = OFPRAW_OFPT12_PACKET_IN;
3240             packet_in_version = OFP12_VERSION;
3241             packet_in_size = sizeof (struct ofp12_packet_in);
3242         } else {
3243             packet_in_raw = OFPRAW_OFPT13_PACKET_IN;
3244             packet_in_version = OFP13_VERSION;
3245             packet_in_size = sizeof (struct ofp13_packet_in);
3246         }
3247
3248         ofputil_packet_in_to_match(pin, &match);
3249
3250         /* The final argument is just an estimate of the space required. */
3251         packet = ofpraw_alloc_xid(packet_in_raw, packet_in_version,
3252                                   htonl(0), (sizeof(struct flow_metadata) * 2
3253                                              + 2 + pin->packet_len));
3254         ofpbuf_put_zeros(packet, packet_in_size);
3255         oxm_put_match(packet, &match);
3256         ofpbuf_put_zeros(packet, 2);
3257         ofpbuf_put(packet, pin->packet, pin->packet_len);
3258
3259         opi = packet->l3;
3260         opi->pi.buffer_id = htonl(pin->buffer_id);
3261         opi->pi.total_len = htons(pin->total_len);
3262         opi->pi.reason = pin->reason;
3263         opi->pi.table_id = pin->table_id;
3264         if (protocol == OFPUTIL_P_OF13_OXM) {
3265             opi->cookie = pin->cookie;
3266         }
3267     } else if (packet_in_format == NXPIF_OPENFLOW10) {
3268         struct ofp10_packet_in *opi;
3269
3270         packet = ofpraw_alloc_xid(OFPRAW_OFPT10_PACKET_IN, OFP10_VERSION,
3271                                   htonl(0), pin->packet_len);
3272         opi = ofpbuf_put_zeros(packet, offsetof(struct ofp10_packet_in, data));
3273         opi->total_len = htons(pin->total_len);
3274         opi->in_port = htons(ofp_to_u16(pin->fmd.in_port));
3275         opi->reason = pin->reason;
3276         opi->buffer_id = htonl(pin->buffer_id);
3277
3278         ofpbuf_put(packet, pin->packet, pin->packet_len);
3279     } else if (packet_in_format == NXPIF_NXM) {
3280         struct nx_packet_in *npi;
3281         struct match match;
3282         size_t match_len;
3283
3284         ofputil_packet_in_to_match(pin, &match);
3285
3286         /* The final argument is just an estimate of the space required. */
3287         packet = ofpraw_alloc_xid(OFPRAW_NXT_PACKET_IN, OFP10_VERSION,
3288                                   htonl(0), (sizeof(struct flow_metadata) * 2
3289                                              + 2 + pin->packet_len));
3290         ofpbuf_put_zeros(packet, sizeof *npi);
3291         match_len = nx_put_match(packet, &match, 0, 0);
3292         ofpbuf_put_zeros(packet, 2);
3293         ofpbuf_put(packet, pin->packet, pin->packet_len);
3294
3295         npi = packet->l3;
3296         npi->buffer_id = htonl(pin->buffer_id);
3297         npi->total_len = htons(pin->total_len);
3298         npi->reason = pin->reason;
3299         npi->table_id = pin->table_id;
3300         npi->cookie = pin->cookie;
3301         npi->match_len = htons(match_len);
3302     } else {
3303         NOT_REACHED();
3304     }
3305     ofpmsg_update_length(packet);
3306
3307     return packet;
3308 }
3309
3310 /* Returns a string form of 'reason'.  The return value is either a statically
3311  * allocated constant string or the 'bufsize'-byte buffer 'reasonbuf'.
3312  * 'bufsize' should be at least OFPUTIL_PACKET_IN_REASON_BUFSIZE. */
3313 const char *
3314 ofputil_packet_in_reason_to_string(enum ofp_packet_in_reason reason,
3315                                    char *reasonbuf, size_t bufsize)
3316 {
3317     switch (reason) {
3318     case OFPR_NO_MATCH:
3319         return "no_match";
3320     case OFPR_ACTION:
3321         return "action";
3322     case OFPR_INVALID_TTL:
3323         return "invalid_ttl";
3324
3325     case OFPR_N_REASONS:
3326     default:
3327         snprintf(reasonbuf, bufsize, "%d", (int) reason);
3328         return reasonbuf;
3329     }
3330 }
3331
3332 bool
3333 ofputil_packet_in_reason_from_string(const char *s,
3334                                      enum ofp_packet_in_reason *reason)
3335 {
3336     int i;
3337
3338     for (i = 0; i < OFPR_N_REASONS; i++) {
3339         char reasonbuf[OFPUTIL_PACKET_IN_REASON_BUFSIZE];
3340         const char *reason_s;
3341
3342         reason_s = ofputil_packet_in_reason_to_string(i, reasonbuf,
3343                                                       sizeof reasonbuf);
3344         if (!strcasecmp(s, reason_s)) {
3345             *reason = i;
3346             return true;
3347         }
3348     }
3349     return false;
3350 }
3351
3352 /* Converts an OFPT_PACKET_OUT in 'opo' into an abstract ofputil_packet_out in
3353  * 'po'.
3354  *
3355  * Uses 'ofpacts' to store the abstract OFPACT_* version of the packet out
3356  * message's actions.  The caller must initialize 'ofpacts' and retains
3357  * ownership of it.  'po->ofpacts' will point into the 'ofpacts' buffer.
3358  *
3359  * Returns 0 if successful, otherwise an OFPERR_* value. */
3360 enum ofperr
3361 ofputil_decode_packet_out(struct ofputil_packet_out *po,
3362                           const struct ofp_header *oh,
3363                           struct ofpbuf *ofpacts)
3364 {
3365     enum ofpraw raw;
3366     struct ofpbuf b;
3367
3368     ofpbuf_use_const(&b, oh, ntohs(oh->length));
3369     raw = ofpraw_pull_assert(&b);
3370
3371     if (raw == OFPRAW_OFPT11_PACKET_OUT) {
3372         enum ofperr error;
3373         const struct ofp11_packet_out *opo = ofpbuf_pull(&b, sizeof *opo);
3374
3375         po->buffer_id = ntohl(opo->buffer_id);
3376         error = ofputil_port_from_ofp11(opo->in_port, &po->in_port);
3377         if (error) {
3378             return error;
3379         }
3380
3381         error = ofpacts_pull_openflow_actions(&b, ntohs(opo->actions_len),
3382                                               oh->version, ofpacts);
3383         if (error) {
3384             return error;
3385         }
3386     } else if (raw == OFPRAW_OFPT10_PACKET_OUT) {
3387         enum ofperr error;
3388         const struct ofp10_packet_out *opo = ofpbuf_pull(&b, sizeof *opo);
3389
3390         po->buffer_id = ntohl(opo->buffer_id);
3391         po->in_port = u16_to_ofp(ntohs(opo->in_port));
3392
3393         error = ofpacts_pull_openflow_actions(&b, ntohs(opo->actions_len),
3394                                               oh->version, ofpacts);
3395         if (error) {
3396             return error;
3397         }
3398     } else {
3399         NOT_REACHED();
3400     }
3401
3402     if (ofp_to_u16(po->in_port) >= ofp_to_u16(OFPP_MAX)
3403         && po->in_port != OFPP_LOCAL
3404         && po->in_port != OFPP_NONE && po->in_port != OFPP_CONTROLLER) {
3405         VLOG_WARN_RL(&bad_ofmsg_rl, "packet-out has bad input port %#"PRIx16,
3406                      po->in_port);
3407         return OFPERR_OFPBRC_BAD_PORT;
3408     }
3409
3410     po->ofpacts = ofpacts->data;
3411     po->ofpacts_len = ofpacts->size;
3412
3413     if (po->buffer_id == UINT32_MAX) {
3414         po->packet = b.data;
3415         po->packet_len = b.size;
3416     } else {
3417         po->packet = NULL;
3418         po->packet_len = 0;
3419     }
3420
3421     return 0;
3422 }
3423 \f
3424 /* ofputil_phy_port */
3425
3426 /* NETDEV_F_* to and from OFPPF_* and OFPPF10_*. */
3427 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_HD    == OFPPF_10MB_HD);  /* bit 0 */
3428 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_FD    == OFPPF_10MB_FD);  /* bit 1 */
3429 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_HD   == OFPPF_100MB_HD); /* bit 2 */
3430 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_FD   == OFPPF_100MB_FD); /* bit 3 */
3431 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_HD     == OFPPF_1GB_HD);   /* bit 4 */
3432 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_FD     == OFPPF_1GB_FD);   /* bit 5 */
3433 BUILD_ASSERT_DECL((int) NETDEV_F_10GB_FD    == OFPPF_10GB_FD);  /* bit 6 */
3434
3435 /* NETDEV_F_ bits 11...15 are OFPPF10_ bits 7...11: */
3436 BUILD_ASSERT_DECL((int) NETDEV_F_COPPER == (OFPPF10_COPPER << 4));
3437 BUILD_ASSERT_DECL((int) NETDEV_F_FIBER == (OFPPF10_FIBER << 4));
3438 BUILD_ASSERT_DECL((int) NETDEV_F_AUTONEG == (OFPPF10_AUTONEG << 4));
3439 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE == (OFPPF10_PAUSE << 4));
3440 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE_ASYM == (OFPPF10_PAUSE_ASYM << 4));
3441
3442 static enum netdev_features
3443 netdev_port_features_from_ofp10(ovs_be32 ofp10_)
3444 {
3445     uint32_t ofp10 = ntohl(ofp10_);
3446     return (ofp10 & 0x7f) | ((ofp10 & 0xf80) << 4);
3447 }
3448
3449 static ovs_be32
3450 netdev_port_features_to_ofp10(enum netdev_features features)
3451 {
3452     return htonl((features & 0x7f) | ((features & 0xf800) >> 4));
3453 }
3454
3455 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_HD    == OFPPF_10MB_HD);     /* bit 0 */
3456 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_FD    == OFPPF_10MB_FD);     /* bit 1 */
3457 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_HD   == OFPPF_100MB_HD);    /* bit 2 */
3458 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_FD   == OFPPF_100MB_FD);    /* bit 3 */
3459 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_HD     == OFPPF_1GB_HD);      /* bit 4 */
3460 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_FD     == OFPPF_1GB_FD);      /* bit 5 */
3461 BUILD_ASSERT_DECL((int) NETDEV_F_10GB_FD    == OFPPF_10GB_FD);     /* bit 6 */
3462 BUILD_ASSERT_DECL((int) NETDEV_F_40GB_FD    == OFPPF11_40GB_FD);   /* bit 7 */
3463 BUILD_ASSERT_DECL((int) NETDEV_F_100GB_FD   == OFPPF11_100GB_FD);  /* bit 8 */
3464 BUILD_ASSERT_DECL((int) NETDEV_F_1TB_FD     == OFPPF11_1TB_FD);    /* bit 9 */
3465 BUILD_ASSERT_DECL((int) NETDEV_F_OTHER      == OFPPF11_OTHER);     /* bit 10 */
3466 BUILD_ASSERT_DECL((int) NETDEV_F_COPPER     == OFPPF11_COPPER);    /* bit 11 */
3467 BUILD_ASSERT_DECL((int) NETDEV_F_FIBER      == OFPPF11_FIBER);     /* bit 12 */
3468 BUILD_ASSERT_DECL((int) NETDEV_F_AUTONEG    == OFPPF11_AUTONEG);   /* bit 13 */
3469 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE      == OFPPF11_PAUSE);     /* bit 14 */
3470 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE_ASYM == OFPPF11_PAUSE_ASYM);/* bit 15 */
3471
3472 static enum netdev_features
3473 netdev_port_features_from_ofp11(ovs_be32 ofp11)
3474 {
3475     return ntohl(ofp11) & 0xffff;
3476 }
3477
3478 static ovs_be32
3479 netdev_port_features_to_ofp11(enum netdev_features features)
3480 {
3481     return htonl(features & 0xffff);
3482 }
3483
3484 static enum ofperr
3485 ofputil_decode_ofp10_phy_port(struct ofputil_phy_port *pp,
3486                               const struct ofp10_phy_port *opp)
3487 {
3488     memset(pp, 0, sizeof *pp);
3489
3490     pp->port_no = u16_to_ofp(ntohs(opp->port_no));
3491     memcpy(pp->hw_addr, opp->hw_addr, OFP_ETH_ALEN);
3492     ovs_strlcpy(pp->name, opp->name, OFP_MAX_PORT_NAME_LEN);
3493
3494     pp->config = ntohl(opp->config) & OFPPC10_ALL;
3495     pp->state = ntohl(opp->state) & OFPPS10_ALL;
3496
3497     pp->curr = netdev_port_features_from_ofp10(opp->curr);
3498     pp->advertised = netdev_port_features_from_ofp10(opp->advertised);
3499     pp->supported = netdev_port_features_from_ofp10(opp->supported);
3500     pp->peer = netdev_port_features_from_ofp10(opp->peer);
3501
3502     pp->curr_speed = netdev_features_to_bps(pp->curr, 0) / 1000;
3503     pp->max_speed = netdev_features_to_bps(pp->supported, 0) / 1000;
3504
3505     return 0;
3506 }
3507
3508 static enum ofperr
3509 ofputil_decode_ofp11_port(struct ofputil_phy_port *pp,
3510                           const struct ofp11_port *op)
3511 {
3512     enum ofperr error;
3513
3514     memset(pp, 0, sizeof *pp);
3515
3516     error = ofputil_port_from_ofp11(op->port_no, &pp->port_no);
3517     if (error) {
3518         return error;
3519     }
3520     memcpy(pp->hw_addr, op->hw_addr, OFP_ETH_ALEN);
3521     ovs_strlcpy(pp->name, op->name, OFP_MAX_PORT_NAME_LEN);
3522
3523     pp->config = ntohl(op->config) & OFPPC11_ALL;
3524     pp->state = ntohl(op->state) & OFPPC11_ALL;
3525
3526     pp->curr = netdev_port_features_from_ofp11(op->curr);
3527     pp->advertised = netdev_port_features_from_ofp11(op->advertised);
3528     pp->supported = netdev_port_features_from_ofp11(op->supported);
3529     pp->peer = netdev_port_features_from_ofp11(op->peer);
3530
3531     pp->curr_speed = ntohl(op->curr_speed);
3532     pp->max_speed = ntohl(op->max_speed);
3533
3534     return 0;
3535 }
3536
3537 static size_t
3538 ofputil_get_phy_port_size(enum ofp_version ofp_version)
3539 {
3540     switch (ofp_version) {
3541     case OFP10_VERSION:
3542         return sizeof(struct ofp10_phy_port);
3543     case OFP11_VERSION:
3544     case OFP12_VERSION:
3545     case OFP13_VERSION:
3546         return sizeof(struct ofp11_port);
3547     default:
3548         NOT_REACHED();
3549     }
3550 }
3551
3552 static void
3553 ofputil_encode_ofp10_phy_port(const struct ofputil_phy_port *pp,
3554                               struct ofp10_phy_port *opp)
3555 {
3556     memset(opp, 0, sizeof *opp);
3557
3558     opp->port_no = htons(ofp_to_u16(pp->port_no));
3559     memcpy(opp->hw_addr, pp->hw_addr, ETH_ADDR_LEN);
3560     ovs_strlcpy(opp->name, pp->name, OFP_MAX_PORT_NAME_LEN);
3561
3562     opp->config = htonl(pp->config & OFPPC10_ALL);
3563     opp->state = htonl(pp->state & OFPPS10_ALL);
3564
3565     opp->curr = netdev_port_features_to_ofp10(pp->curr);
3566     opp->advertised = netdev_port_features_to_ofp10(pp->advertised);
3567     opp->supported = netdev_port_features_to_ofp10(pp->supported);
3568     opp->peer = netdev_port_features_to_ofp10(pp->peer);
3569 }
3570
3571 static void
3572 ofputil_encode_ofp11_port(const struct ofputil_phy_port *pp,
3573                           struct ofp11_port *op)
3574 {
3575     memset(op, 0, sizeof *op);
3576
3577     op->port_no = ofputil_port_to_ofp11(pp->port_no);
3578     memcpy(op->hw_addr, pp->hw_addr, ETH_ADDR_LEN);
3579     ovs_strlcpy(op->name, pp->name, OFP_MAX_PORT_NAME_LEN);
3580
3581     op->config = htonl(pp->config & OFPPC11_ALL);
3582     op->state = htonl(pp->state & OFPPS11_ALL);
3583
3584     op->curr = netdev_port_features_to_ofp11(pp->curr);
3585     op->advertised = netdev_port_features_to_ofp11(pp->advertised);
3586     op->supported = netdev_port_features_to_ofp11(pp->supported);
3587     op->peer = netdev_port_features_to_ofp11(pp->peer);
3588
3589     op->curr_speed = htonl(pp->curr_speed);
3590     op->max_speed = htonl(pp->max_speed);
3591 }
3592
3593 static void
3594 ofputil_put_phy_port(enum ofp_version ofp_version,
3595                      const struct ofputil_phy_port *pp, struct ofpbuf *b)
3596 {
3597     switch (ofp_version) {
3598     case OFP10_VERSION: {
3599         struct ofp10_phy_port *opp;
3600         if (b->size + sizeof *opp <= UINT16_MAX) {
3601             opp = ofpbuf_put_uninit(b, sizeof *opp);
3602             ofputil_encode_ofp10_phy_port(pp, opp);
3603         }
3604         break;
3605     }
3606
3607     case OFP11_VERSION:
3608     case OFP12_VERSION:
3609     case OFP13_VERSION: {
3610         struct ofp11_port *op;
3611         if (b->size + sizeof *op <= UINT16_MAX) {
3612             op = ofpbuf_put_uninit(b, sizeof *op);
3613             ofputil_encode_ofp11_port(pp, op);
3614         }
3615         break;
3616     }
3617
3618     default:
3619         NOT_REACHED();
3620     }
3621 }
3622
3623 void
3624 ofputil_append_port_desc_stats_reply(enum ofp_version ofp_version,
3625                                      const struct ofputil_phy_port *pp,
3626                                      struct list *replies)
3627 {
3628     switch (ofp_version) {
3629     case OFP10_VERSION: {
3630         struct ofp10_phy_port *opp;
3631
3632         opp = ofpmp_append(replies, sizeof *opp);
3633         ofputil_encode_ofp10_phy_port(pp, opp);
3634         break;
3635     }
3636
3637     case OFP11_VERSION:
3638     case OFP12_VERSION:
3639     case OFP13_VERSION: {
3640         struct ofp11_port *op;
3641
3642         op = ofpmp_append(replies, sizeof *op);
3643         ofputil_encode_ofp11_port(pp, op);
3644         break;
3645     }
3646
3647     default:
3648       NOT_REACHED();
3649     }
3650 }
3651 \f
3652 /* ofputil_switch_features */
3653
3654 #define OFPC_COMMON (OFPC_FLOW_STATS | OFPC_TABLE_STATS | OFPC_PORT_STATS | \
3655                      OFPC_IP_REASM | OFPC_QUEUE_STATS)
3656 BUILD_ASSERT_DECL((int) OFPUTIL_C_FLOW_STATS == OFPC_FLOW_STATS);
3657 BUILD_ASSERT_DECL((int) OFPUTIL_C_TABLE_STATS == OFPC_TABLE_STATS);
3658 BUILD_ASSERT_DECL((int) OFPUTIL_C_PORT_STATS == OFPC_PORT_STATS);
3659 BUILD_ASSERT_DECL((int) OFPUTIL_C_IP_REASM == OFPC_IP_REASM);
3660 BUILD_ASSERT_DECL((int) OFPUTIL_C_QUEUE_STATS == OFPC_QUEUE_STATS);
3661 BUILD_ASSERT_DECL((int) OFPUTIL_C_ARP_MATCH_IP == OFPC_ARP_MATCH_IP);
3662
3663 struct ofputil_action_bit_translation {
3664     enum ofputil_action_bitmap ofputil_bit;
3665     int of_bit;
3666 };
3667
3668 static const struct ofputil_action_bit_translation of10_action_bits[] = {
3669     { OFPUTIL_A_OUTPUT,       OFPAT10_OUTPUT },
3670     { OFPUTIL_A_SET_VLAN_VID, OFPAT10_SET_VLAN_VID },
3671     { OFPUTIL_A_SET_VLAN_PCP, OFPAT10_SET_VLAN_PCP },
3672     { OFPUTIL_A_STRIP_VLAN,   OFPAT10_STRIP_VLAN },
3673     { OFPUTIL_A_SET_DL_SRC,   OFPAT10_SET_DL_SRC },
3674     { OFPUTIL_A_SET_DL_DST,   OFPAT10_SET_DL_DST },
3675     { OFPUTIL_A_SET_NW_SRC,   OFPAT10_SET_NW_SRC },
3676     { OFPUTIL_A_SET_NW_DST,   OFPAT10_SET_NW_DST },
3677     { OFPUTIL_A_SET_NW_TOS,   OFPAT10_SET_NW_TOS },
3678     { OFPUTIL_A_SET_TP_SRC,   OFPAT10_SET_TP_SRC },
3679     { OFPUTIL_A_SET_TP_DST,   OFPAT10_SET_TP_DST },
3680     { OFPUTIL_A_ENQUEUE,      OFPAT10_ENQUEUE },
3681     { 0, 0 },
3682 };
3683
3684 static enum ofputil_action_bitmap
3685 decode_action_bits(ovs_be32 of_actions,
3686                    const struct ofputil_action_bit_translation *x)
3687 {
3688     enum ofputil_action_bitmap ofputil_actions;
3689
3690     ofputil_actions = 0;
3691     for (; x->ofputil_bit; x++) {
3692         if (of_actions & htonl(1u << x->of_bit)) {
3693             ofputil_actions |= x->ofputil_bit;
3694         }
3695     }
3696     return ofputil_actions;
3697 }
3698
3699 static uint32_t
3700 ofputil_capabilities_mask(enum ofp_version ofp_version)
3701 {
3702     /* Handle capabilities whose bit is unique for all Open Flow versions */
3703     switch (ofp_version) {
3704     case OFP10_VERSION:
3705     case OFP11_VERSION:
3706         return OFPC_COMMON | OFPC_ARP_MATCH_IP;
3707     case OFP12_VERSION:
3708     case OFP13_VERSION:
3709         return OFPC_COMMON | OFPC12_PORT_BLOCKED;
3710     default:
3711         /* Caller needs to check osf->header.version itself */
3712         return 0;
3713     }
3714 }
3715
3716 /* Decodes an OpenFlow 1.0 or 1.1 "switch_features" structure 'osf' into an
3717  * abstract representation in '*features'.  Initializes '*b' to iterate over
3718  * the OpenFlow port structures following 'osf' with later calls to
3719  * ofputil_pull_phy_port().  Returns 0 if successful, otherwise an
3720  * OFPERR_* value.  */
3721 enum ofperr
3722 ofputil_decode_switch_features(const struct ofp_header *oh,
3723                                struct ofputil_switch_features *features,
3724                                struct ofpbuf *b)
3725 {
3726     const struct ofp_switch_features *osf;
3727     enum ofpraw raw;
3728
3729     ofpbuf_use_const(b, oh, ntohs(oh->length));
3730     raw = ofpraw_pull_assert(b);
3731
3732     osf = ofpbuf_pull(b, sizeof *osf);
3733     features->datapath_id = ntohll(osf->datapath_id);
3734     features->n_buffers = ntohl(osf->n_buffers);
3735     features->n_tables = osf->n_tables;
3736     features->auxiliary_id = 0;
3737
3738     features->capabilities = ntohl(osf->capabilities) &
3739         ofputil_capabilities_mask(oh->version);
3740
3741     if (b->size % ofputil_get_phy_port_size(oh->version)) {
3742         return OFPERR_OFPBRC_BAD_LEN;
3743     }
3744
3745     if (raw == OFPRAW_OFPT10_FEATURES_REPLY) {
3746         if (osf->capabilities & htonl(OFPC10_STP)) {
3747             features->capabilities |= OFPUTIL_C_STP;
3748         }
3749         features->actions = decode_action_bits(osf->actions, of10_action_bits);
3750     } else if (raw == OFPRAW_OFPT11_FEATURES_REPLY
3751                || raw == OFPRAW_OFPT13_FEATURES_REPLY) {
3752         if (osf->capabilities & htonl(OFPC11_GROUP_STATS)) {
3753             features->capabilities |= OFPUTIL_C_GROUP_STATS;
3754         }
3755         features->actions = 0;
3756         if (raw == OFPRAW_OFPT13_FEATURES_REPLY) {
3757             features->auxiliary_id = osf->auxiliary_id;
3758         }
3759     } else {
3760         return OFPERR_OFPBRC_BAD_VERSION;
3761     }
3762
3763     return 0;
3764 }
3765
3766 /* Returns true if the maximum number of ports are in 'oh'. */
3767 static bool
3768 max_ports_in_features(const struct ofp_header *oh)
3769 {
3770     size_t pp_size = ofputil_get_phy_port_size(oh->version);
3771     return ntohs(oh->length) + pp_size > UINT16_MAX;
3772 }
3773
3774 /* Given a buffer 'b' that contains a Features Reply message, checks if
3775  * it contains the maximum number of ports that will fit.  If so, it
3776  * returns true and removes the ports from the message.  The caller
3777  * should then send an OFPST_PORT_DESC stats request to get the ports,
3778  * since the switch may have more ports than could be represented in the
3779  * Features Reply.  Otherwise, returns false.
3780  */
3781 bool
3782 ofputil_switch_features_ports_trunc(struct ofpbuf *b)
3783 {
3784     struct ofp_header *oh = b->data;
3785
3786     if (max_ports_in_features(oh)) {
3787         /* Remove all the ports. */
3788         b->size = (sizeof(struct ofp_header)
3789                    + sizeof(struct ofp_switch_features));
3790         ofpmsg_update_length(b);
3791
3792         return true;
3793     }
3794
3795     return false;
3796 }
3797
3798 static ovs_be32
3799 encode_action_bits(enum ofputil_action_bitmap ofputil_actions,
3800                    const struct ofputil_action_bit_translation *x)
3801 {
3802     uint32_t of_actions;
3803
3804     of_actions = 0;
3805     for (; x->ofputil_bit; x++) {
3806         if (ofputil_actions & x->ofputil_bit) {
3807             of_actions |= 1 << x->of_bit;
3808         }
3809     }
3810     return htonl(of_actions);
3811 }
3812
3813 /* Returns a buffer owned by the caller that encodes 'features' in the format
3814  * required by 'protocol' with the given 'xid'.  The caller should append port
3815  * information to the buffer with subsequent calls to
3816  * ofputil_put_switch_features_port(). */
3817 struct ofpbuf *
3818 ofputil_encode_switch_features(const struct ofputil_switch_features *features,
3819                                enum ofputil_protocol protocol, ovs_be32 xid)
3820 {
3821     struct ofp_switch_features *osf;
3822     struct ofpbuf *b;
3823     enum ofp_version version;
3824     enum ofpraw raw;
3825
3826     version = ofputil_protocol_to_ofp_version(protocol);
3827     switch (version) {
3828     case OFP10_VERSION:
3829         raw = OFPRAW_OFPT10_FEATURES_REPLY;
3830         break;
3831     case OFP11_VERSION:
3832     case OFP12_VERSION:
3833         raw = OFPRAW_OFPT11_FEATURES_REPLY;
3834         break;
3835     case OFP13_VERSION:
3836         raw = OFPRAW_OFPT13_FEATURES_REPLY;
3837         break;
3838     default:
3839         NOT_REACHED();
3840     }
3841     b = ofpraw_alloc_xid(raw, version, xid, 0);
3842     osf = ofpbuf_put_zeros(b, sizeof *osf);
3843     osf->datapath_id = htonll(features->datapath_id);
3844     osf->n_buffers = htonl(features->n_buffers);
3845     osf->n_tables = features->n_tables;
3846
3847     osf->capabilities = htonl(features->capabilities & OFPC_COMMON);
3848     osf->capabilities = htonl(features->capabilities &
3849                               ofputil_capabilities_mask(version));
3850     switch (version) {
3851     case OFP10_VERSION:
3852         if (features->capabilities & OFPUTIL_C_STP) {
3853             osf->capabilities |= htonl(OFPC10_STP);
3854         }
3855         osf->actions = encode_action_bits(features->actions, of10_action_bits);
3856         break;
3857     case OFP13_VERSION:
3858         osf->auxiliary_id = features->auxiliary_id;
3859         /* fall through */
3860     case OFP11_VERSION:
3861     case OFP12_VERSION:
3862         if (features->capabilities & OFPUTIL_C_GROUP_STATS) {
3863             osf->capabilities |= htonl(OFPC11_GROUP_STATS);
3864         }
3865         break;
3866     default:
3867         NOT_REACHED();
3868     }
3869
3870     return b;
3871 }
3872
3873 /* Encodes 'pp' into the format required by the switch_features message already
3874  * in 'b', which should have been returned by ofputil_encode_switch_features(),
3875  * and appends the encoded version to 'b'. */
3876 void
3877 ofputil_put_switch_features_port(const struct ofputil_phy_port *pp,
3878                                  struct ofpbuf *b)
3879 {
3880     const struct ofp_header *oh = b->data;
3881
3882     if (oh->version < OFP13_VERSION) {
3883         ofputil_put_phy_port(oh->version, pp, b);
3884     }
3885 }
3886 \f
3887 /* ofputil_port_status */
3888
3889 /* Decodes the OpenFlow "port status" message in '*ops' into an abstract form
3890  * in '*ps'.  Returns 0 if successful, otherwise an OFPERR_* value. */
3891 enum ofperr
3892 ofputil_decode_port_status(const struct ofp_header *oh,
3893                            struct ofputil_port_status *ps)
3894 {
3895     const struct ofp_port_status *ops;
3896     struct ofpbuf b;
3897     int retval;
3898
3899     ofpbuf_use_const(&b, oh, ntohs(oh->length));
3900     ofpraw_pull_assert(&b);
3901     ops = ofpbuf_pull(&b, sizeof *ops);
3902
3903     if (ops->reason != OFPPR_ADD &&
3904         ops->reason != OFPPR_DELETE &&
3905         ops->reason != OFPPR_MODIFY) {
3906         return OFPERR_NXBRC_BAD_REASON;
3907     }
3908     ps->reason = ops->reason;
3909
3910     retval = ofputil_pull_phy_port(oh->version, &b, &ps->desc);
3911     ovs_assert(retval != EOF);
3912     return retval;
3913 }
3914
3915 /* Converts the abstract form of a "port status" message in '*ps' into an
3916  * OpenFlow message suitable for 'protocol', and returns that encoded form in
3917  * a buffer owned by the caller. */
3918 struct ofpbuf *
3919 ofputil_encode_port_status(const struct ofputil_port_status *ps,
3920                            enum ofputil_protocol protocol)
3921 {
3922     struct ofp_port_status *ops;
3923     struct ofpbuf *b;
3924     enum ofp_version version;
3925     enum ofpraw raw;
3926
3927     version = ofputil_protocol_to_ofp_version(protocol);
3928     switch (version) {
3929     case OFP10_VERSION:
3930         raw = OFPRAW_OFPT10_PORT_STATUS;
3931         break;
3932
3933     case OFP11_VERSION:
3934     case OFP12_VERSION:
3935     case OFP13_VERSION:
3936         raw = OFPRAW_OFPT11_PORT_STATUS;
3937         break;
3938
3939     default:
3940         NOT_REACHED();
3941     }
3942
3943     b = ofpraw_alloc_xid(raw, version, htonl(0), 0);
3944     ops = ofpbuf_put_zeros(b, sizeof *ops);
3945     ops->reason = ps->reason;
3946     ofputil_put_phy_port(version, &ps->desc, b);
3947     ofpmsg_update_length(b);
3948     return b;
3949 }
3950
3951 /* ofputil_port_mod */
3952
3953 /* Decodes the OpenFlow "port mod" message in '*oh' into an abstract form in
3954  * '*pm'.  Returns 0 if successful, otherwise an OFPERR_* value. */
3955 enum ofperr
3956 ofputil_decode_port_mod(const struct ofp_header *oh,
3957                         struct ofputil_port_mod *pm)
3958 {
3959     enum ofpraw raw;
3960     struct ofpbuf b;
3961
3962     ofpbuf_use_const(&b, oh, ntohs(oh->length));
3963     raw = ofpraw_pull_assert(&b);
3964
3965     if (raw == OFPRAW_OFPT10_PORT_MOD) {
3966         const struct ofp10_port_mod *opm = b.data;
3967
3968         pm->port_no = u16_to_ofp(ntohs(opm->port_no));
3969         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
3970         pm->config = ntohl(opm->config) & OFPPC10_ALL;
3971         pm->mask = ntohl(opm->mask) & OFPPC10_ALL;
3972         pm->advertise = netdev_port_features_from_ofp10(opm->advertise);
3973     } else if (raw == OFPRAW_OFPT11_PORT_MOD) {
3974         const struct ofp11_port_mod *opm = b.data;
3975         enum ofperr error;
3976
3977         error = ofputil_port_from_ofp11(opm->port_no, &pm->port_no);
3978         if (error) {
3979             return error;
3980         }
3981
3982         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
3983         pm->config = ntohl(opm->config) & OFPPC11_ALL;
3984         pm->mask = ntohl(opm->mask) & OFPPC11_ALL;
3985         pm->advertise = netdev_port_features_from_ofp11(opm->advertise);
3986     } else {
3987         return OFPERR_OFPBRC_BAD_TYPE;
3988     }
3989
3990     pm->config &= pm->mask;
3991     return 0;
3992 }
3993
3994 /* Converts the abstract form of a "port mod" message in '*pm' into an OpenFlow
3995  * message suitable for 'protocol', and returns that encoded form in a buffer
3996  * owned by the caller. */
3997 struct ofpbuf *
3998 ofputil_encode_port_mod(const struct ofputil_port_mod *pm,
3999                         enum ofputil_protocol protocol)
4000 {
4001     enum ofp_version ofp_version = ofputil_protocol_to_ofp_version(protocol);
4002     struct ofpbuf *b;
4003
4004     switch (ofp_version) {
4005     case OFP10_VERSION: {
4006         struct ofp10_port_mod *opm;
4007
4008         b = ofpraw_alloc(OFPRAW_OFPT10_PORT_MOD, ofp_version, 0);
4009         opm = ofpbuf_put_zeros(b, sizeof *opm);
4010         opm->port_no = htons(ofp_to_u16(pm->port_no));
4011         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
4012         opm->config = htonl(pm->config & OFPPC10_ALL);
4013         opm->mask = htonl(pm->mask & OFPPC10_ALL);
4014         opm->advertise = netdev_port_features_to_ofp10(pm->advertise);
4015         break;
4016     }
4017
4018     case OFP11_VERSION:
4019     case OFP12_VERSION:
4020     case OFP13_VERSION: {
4021         struct ofp11_port_mod *opm;
4022
4023         b = ofpraw_alloc(OFPRAW_OFPT11_PORT_MOD, ofp_version, 0);
4024         opm = ofpbuf_put_zeros(b, sizeof *opm);
4025         opm->port_no = ofputil_port_to_ofp11(pm->port_no);
4026         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
4027         opm->config = htonl(pm->config & OFPPC11_ALL);
4028         opm->mask = htonl(pm->mask & OFPPC11_ALL);
4029         opm->advertise = netdev_port_features_to_ofp11(pm->advertise);
4030         break;
4031     }
4032     default:
4033         NOT_REACHED();
4034     }
4035
4036     return b;
4037 }
4038
4039 /* ofputil_table_mod */
4040
4041 /* Decodes the OpenFlow "table mod" message in '*oh' into an abstract form in
4042  * '*pm'.  Returns 0 if successful, otherwise an OFPERR_* value. */
4043 enum ofperr
4044 ofputil_decode_table_mod(const struct ofp_header *oh,
4045                          struct ofputil_table_mod *pm)
4046 {
4047     enum ofpraw raw;
4048     struct ofpbuf b;
4049
4050     ofpbuf_use_const(&b, oh, ntohs(oh->length));
4051     raw = ofpraw_pull_assert(&b);
4052
4053     if (raw == OFPRAW_OFPT11_TABLE_MOD) {
4054         const struct ofp11_table_mod *otm = b.data;
4055
4056         pm->table_id = otm->table_id;
4057         pm->config = ntohl(otm->config);
4058     } else {
4059         return OFPERR_OFPBRC_BAD_TYPE;
4060     }
4061
4062     return 0;
4063 }
4064
4065 /* Converts the abstract form of a "table mod" message in '*pm' into an OpenFlow
4066  * message suitable for 'protocol', and returns that encoded form in a buffer
4067  * owned by the caller. */
4068 struct ofpbuf *
4069 ofputil_encode_table_mod(const struct ofputil_table_mod *pm,
4070                         enum ofputil_protocol protocol)
4071 {
4072     enum ofp_version ofp_version = ofputil_protocol_to_ofp_version(protocol);
4073     struct ofpbuf *b;
4074
4075     switch (ofp_version) {
4076     case OFP10_VERSION: {
4077         ovs_fatal(0, "table mod needs OpenFlow 1.1 or later "
4078                      "(\'-O OpenFlow11\')");
4079         break;
4080     }
4081     case OFP11_VERSION:
4082     case OFP12_VERSION:
4083     case OFP13_VERSION: {
4084         struct ofp11_table_mod *otm;
4085
4086         b = ofpraw_alloc(OFPRAW_OFPT11_TABLE_MOD, ofp_version, 0);
4087         otm = ofpbuf_put_zeros(b, sizeof *otm);
4088         otm->table_id = pm->table_id;
4089         otm->config = htonl(pm->config);
4090         break;
4091     }
4092     default:
4093         NOT_REACHED();
4094     }
4095
4096     return b;
4097 }
4098 \f
4099 /* ofputil_role_request */
4100
4101 /* Decodes the OpenFlow "role request" or "role reply" message in '*oh' into
4102  * an abstract form in '*rr'.  Returns 0 if successful, otherwise an
4103  * OFPERR_* value. */
4104 enum ofperr
4105 ofputil_decode_role_message(const struct ofp_header *oh,
4106                             struct ofputil_role_request *rr)
4107 {
4108     struct ofpbuf b;
4109     enum ofpraw raw;
4110
4111     ofpbuf_use_const(&b, oh, ntohs(oh->length));
4112     raw = ofpraw_pull_assert(&b);
4113
4114     if (raw == OFPRAW_OFPT12_ROLE_REQUEST ||
4115         raw == OFPRAW_OFPT12_ROLE_REPLY) {
4116         const struct ofp12_role_request *orr = b.l3;
4117
4118         if (orr->role != htonl(OFPCR12_ROLE_NOCHANGE) &&
4119             orr->role != htonl(OFPCR12_ROLE_EQUAL) &&
4120             orr->role != htonl(OFPCR12_ROLE_MASTER) &&
4121             orr->role != htonl(OFPCR12_ROLE_SLAVE)) {
4122             return OFPERR_OFPRRFC_BAD_ROLE;
4123         }
4124
4125         rr->role = ntohl(orr->role);
4126         if (raw == OFPRAW_OFPT12_ROLE_REQUEST
4127             ? orr->role == htonl(OFPCR12_ROLE_NOCHANGE)
4128             : orr->generation_id == OVS_BE64_MAX) {
4129             rr->have_generation_id = false;
4130             rr->generation_id = 0;
4131         } else {
4132             rr->have_generation_id = true;
4133             rr->generation_id = ntohll(orr->generation_id);
4134         }
4135     } else if (raw == OFPRAW_NXT_ROLE_REQUEST ||
4136                raw == OFPRAW_NXT_ROLE_REPLY) {
4137         const struct nx_role_request *nrr = b.l3;
4138
4139         BUILD_ASSERT(NX_ROLE_OTHER + 1 == OFPCR12_ROLE_EQUAL);
4140         BUILD_ASSERT(NX_ROLE_MASTER + 1 == OFPCR12_ROLE_MASTER);
4141         BUILD_ASSERT(NX_ROLE_SLAVE + 1 == OFPCR12_ROLE_SLAVE);
4142
4143         if (nrr->role != htonl(NX_ROLE_OTHER) &&
4144             nrr->role != htonl(NX_ROLE_MASTER) &&
4145             nrr->role != htonl(NX_ROLE_SLAVE)) {
4146             return OFPERR_OFPRRFC_BAD_ROLE;
4147         }
4148
4149         rr->role = ntohl(nrr->role) + 1;
4150         rr->have_generation_id = false;
4151         rr->generation_id = 0;
4152     } else {
4153         NOT_REACHED();
4154     }
4155
4156     return 0;
4157 }
4158
4159 /* Returns an encoded form of a role reply suitable for the "request" in a
4160  * buffer owned by the caller. */
4161 struct ofpbuf *
4162 ofputil_encode_role_reply(const struct ofp_header *request,
4163                           const struct ofputil_role_request *rr)
4164 {
4165     struct ofpbuf *buf;
4166     enum ofpraw raw;
4167
4168     raw = ofpraw_decode_assert(request);
4169     if (raw == OFPRAW_OFPT12_ROLE_REQUEST) {
4170         struct ofp12_role_request *orr;
4171
4172         buf = ofpraw_alloc_reply(OFPRAW_OFPT12_ROLE_REPLY, request, 0);
4173         orr = ofpbuf_put_zeros(buf, sizeof *orr);
4174
4175         orr->role = htonl(rr->role);
4176         orr->generation_id = htonll(rr->have_generation_id
4177                                     ? rr->generation_id
4178                                     : UINT64_MAX);
4179     } else if (raw == OFPRAW_NXT_ROLE_REQUEST) {
4180         struct nx_role_request *nrr;
4181
4182         BUILD_ASSERT(NX_ROLE_OTHER == OFPCR12_ROLE_EQUAL - 1);
4183         BUILD_ASSERT(NX_ROLE_MASTER == OFPCR12_ROLE_MASTER - 1);
4184         BUILD_ASSERT(NX_ROLE_SLAVE == OFPCR12_ROLE_SLAVE - 1);
4185
4186         buf = ofpraw_alloc_reply(OFPRAW_NXT_ROLE_REPLY, request, 0);
4187         nrr = ofpbuf_put_zeros(buf, sizeof *nrr);
4188         nrr->role = htonl(rr->role - 1);
4189     } else {
4190         NOT_REACHED();
4191     }
4192
4193     return buf;
4194 }
4195 \f
4196 struct ofpbuf *
4197 ofputil_encode_role_status(const struct ofputil_role_status *status,
4198                            enum ofputil_protocol protocol)
4199 {
4200     struct ofpbuf *buf;
4201     enum ofp_version version;
4202     struct ofp14_role_status *rstatus;
4203
4204     version = ofputil_protocol_to_ofp_version(protocol);
4205     buf = ofpraw_alloc_xid(OFPRAW_OFPT14_ROLE_STATUS, version, htonl(0), 0);
4206     rstatus = ofpbuf_put_zeros(buf, sizeof *rstatus);
4207     rstatus->role = htonl(status->role);
4208     rstatus->reason = status->reason;
4209     rstatus->generation_id = htonll(status->generation_id);
4210
4211     return buf;
4212 }
4213
4214 enum ofperr
4215 ofputil_decode_role_status(const struct ofp_header *oh,
4216                            struct ofputil_role_status *rs)
4217 {
4218     struct ofpbuf b;
4219     enum ofpraw raw;
4220     const struct ofp14_role_status *r;
4221
4222     ofpbuf_use_const(&b, oh, ntohs(oh->length));
4223     raw = ofpraw_pull_assert(&b);
4224     ovs_assert(raw == OFPRAW_OFPT14_ROLE_STATUS);
4225
4226     r = b.l3;
4227     if (r->role != htonl(OFPCR12_ROLE_NOCHANGE) &&
4228         r->role != htonl(OFPCR12_ROLE_EQUAL) &&
4229         r->role != htonl(OFPCR12_ROLE_MASTER) &&
4230         r->role != htonl(OFPCR12_ROLE_SLAVE)) {
4231         return OFPERR_OFPRRFC_BAD_ROLE;
4232     }
4233
4234     rs->role = ntohl(r->role);
4235     rs->generation_id = ntohll(r->generation_id);
4236     rs->reason = r->reason;
4237
4238     return 0;
4239 }
4240
4241 /* Table stats. */
4242
4243 static void
4244 ofputil_put_ofp10_table_stats(const struct ofp12_table_stats *in,
4245                               struct ofpbuf *buf)
4246 {
4247     struct wc_map {
4248         enum ofp10_flow_wildcards wc10;
4249         enum oxm12_ofb_match_fields mf12;
4250     };
4251
4252     static const struct wc_map wc_map[] = {
4253         { OFPFW10_IN_PORT,     OFPXMT12_OFB_IN_PORT },
4254         { OFPFW10_DL_VLAN,     OFPXMT12_OFB_VLAN_VID },
4255         { OFPFW10_DL_SRC,      OFPXMT12_OFB_ETH_SRC },
4256         { OFPFW10_DL_DST,      OFPXMT12_OFB_ETH_DST},
4257         { OFPFW10_DL_TYPE,     OFPXMT12_OFB_ETH_TYPE },
4258         { OFPFW10_NW_PROTO,    OFPXMT12_OFB_IP_PROTO },
4259         { OFPFW10_TP_SRC,      OFPXMT12_OFB_TCP_SRC },
4260         { OFPFW10_TP_DST,      OFPXMT12_OFB_TCP_DST },
4261         { OFPFW10_NW_SRC_MASK, OFPXMT12_OFB_IPV4_SRC },
4262         { OFPFW10_NW_DST_MASK, OFPXMT12_OFB_IPV4_DST },
4263         { OFPFW10_DL_VLAN_PCP, OFPXMT12_OFB_VLAN_PCP },
4264         { OFPFW10_NW_TOS,      OFPXMT12_OFB_IP_DSCP },
4265     };
4266
4267     struct ofp10_table_stats *out;
4268     const struct wc_map *p;
4269
4270     out = ofpbuf_put_zeros(buf, sizeof *out);
4271     out->table_id = in->table_id;
4272     ovs_strlcpy(out->name, in->name, sizeof out->name);
4273     out->wildcards = 0;
4274     for (p = wc_map; p < &wc_map[ARRAY_SIZE(wc_map)]; p++) {
4275         if (in->wildcards & htonll(1ULL << p->mf12)) {
4276             out->wildcards |= htonl(p->wc10);
4277         }
4278     }
4279     out->max_entries = in->max_entries;
4280     out->active_count = in->active_count;
4281     put_32aligned_be64(&out->lookup_count, in->lookup_count);
4282     put_32aligned_be64(&out->matched_count, in->matched_count);
4283 }
4284
4285 static ovs_be32
4286 oxm12_to_ofp11_flow_match_fields(ovs_be64 oxm12)
4287 {
4288     struct map {
4289         enum ofp11_flow_match_fields fmf11;
4290         enum oxm12_ofb_match_fields mf12;
4291     };
4292
4293     static const struct map map[] = {
4294         { OFPFMF11_IN_PORT,     OFPXMT12_OFB_IN_PORT },
4295         { OFPFMF11_DL_VLAN,     OFPXMT12_OFB_VLAN_VID },
4296         { OFPFMF11_DL_VLAN_PCP, OFPXMT12_OFB_VLAN_PCP },
4297         { OFPFMF11_DL_TYPE,     OFPXMT12_OFB_ETH_TYPE },
4298         { OFPFMF11_NW_TOS,      OFPXMT12_OFB_IP_DSCP },
4299         { OFPFMF11_NW_PROTO,    OFPXMT12_OFB_IP_PROTO },
4300         { OFPFMF11_TP_SRC,      OFPXMT12_OFB_TCP_SRC },
4301         { OFPFMF11_TP_DST,      OFPXMT12_OFB_TCP_DST },
4302         { OFPFMF11_MPLS_LABEL,  OFPXMT12_OFB_MPLS_LABEL },
4303         { OFPFMF11_MPLS_TC,     OFPXMT12_OFB_MPLS_TC },
4304         /* I don't know what OFPFMF11_TYPE means. */
4305         { OFPFMF11_DL_SRC,      OFPXMT12_OFB_ETH_SRC },
4306         { OFPFMF11_DL_DST,      OFPXMT12_OFB_ETH_DST },
4307         { OFPFMF11_NW_SRC,      OFPXMT12_OFB_IPV4_SRC },
4308         { OFPFMF11_NW_DST,      OFPXMT12_OFB_IPV4_DST },
4309         { OFPFMF11_METADATA,    OFPXMT12_OFB_METADATA },
4310     };
4311
4312     const struct map *p;
4313     uint32_t fmf11;
4314
4315     fmf11 = 0;
4316     for (p = map; p < &map[ARRAY_SIZE(map)]; p++) {
4317         if (oxm12 & htonll(1ULL << p->mf12)) {
4318             fmf11 |= p->fmf11;
4319         }
4320     }
4321     return htonl(fmf11);
4322 }
4323
4324 static void
4325 ofputil_put_ofp11_table_stats(const struct ofp12_table_stats *in,
4326                               struct ofpbuf *buf)
4327 {
4328     struct ofp11_table_stats *out;
4329
4330     out = ofpbuf_put_zeros(buf, sizeof *out);
4331     out->table_id = in->table_id;
4332     ovs_strlcpy(out->name, in->name, sizeof out->name);
4333     out->wildcards = oxm12_to_ofp11_flow_match_fields(in->wildcards);
4334     out->match = oxm12_to_ofp11_flow_match_fields(in->match);
4335     out->instructions = in->instructions;
4336     out->write_actions = in->write_actions;
4337     out->apply_actions = in->apply_actions;
4338     out->config = in->config;
4339     out->max_entries = in->max_entries;
4340     out->active_count = in->active_count;
4341     out->lookup_count = in->lookup_count;
4342     out->matched_count = in->matched_count;
4343 }
4344
4345 static void
4346 ofputil_put_ofp12_table_stats(const struct ofp12_table_stats *in,
4347                               struct ofpbuf *buf)
4348 {
4349     struct ofp12_table_stats *out = ofpbuf_put(buf, in, sizeof *in);
4350
4351     /* Trim off OF1.3-only capabilities. */
4352     out->match &= htonll(OFPXMT12_MASK);
4353     out->wildcards &= htonll(OFPXMT12_MASK);
4354     out->write_setfields &= htonll(OFPXMT12_MASK);
4355     out->apply_setfields &= htonll(OFPXMT12_MASK);
4356 }
4357
4358 static void
4359 ofputil_put_ofp13_table_stats(const struct ofp12_table_stats *in,
4360                               struct ofpbuf *buf)
4361 {
4362     struct ofp13_table_stats *out;
4363
4364     /* OF 1.3 splits table features off the ofp_table_stats,
4365      * so there is not much here. */
4366
4367     out = ofpbuf_put_uninit(buf, sizeof *out);
4368     out->table_id = in->table_id;
4369     out->active_count = in->active_count;
4370     out->lookup_count = in->lookup_count;
4371     out->matched_count = in->matched_count;
4372 }
4373
4374 struct ofpbuf *
4375 ofputil_encode_table_stats_reply(const struct ofp12_table_stats stats[], int n,
4376                                  const struct ofp_header *request)
4377 {
4378     struct ofpbuf *reply;
4379     int i;
4380
4381     reply = ofpraw_alloc_stats_reply(request, n * sizeof *stats);
4382
4383     for (i = 0; i < n; i++) {
4384         switch ((enum ofp_version) request->version) {
4385         case OFP10_VERSION:
4386             ofputil_put_ofp10_table_stats(&stats[i], reply);
4387             break;
4388
4389         case OFP11_VERSION:
4390             ofputil_put_ofp11_table_stats(&stats[i], reply);
4391             break;
4392
4393         case OFP12_VERSION:
4394             ofputil_put_ofp12_table_stats(&stats[i], reply);
4395             break;
4396
4397         case OFP13_VERSION:
4398             ofputil_put_ofp13_table_stats(&stats[i], reply);
4399             break;
4400
4401         default:
4402             NOT_REACHED();
4403         }
4404     }
4405
4406     return reply;
4407 }
4408 \f
4409 /* ofputil_flow_monitor_request */
4410
4411 /* Converts an NXST_FLOW_MONITOR request in 'msg' into an abstract
4412  * ofputil_flow_monitor_request in 'rq'.
4413  *
4414  * Multiple NXST_FLOW_MONITOR requests can be packed into a single OpenFlow
4415  * message.  Calling this function multiple times for a single 'msg' iterates
4416  * through the requests.  The caller must initially leave 'msg''s layer
4417  * pointers null and not modify them between calls.
4418  *
4419  * Returns 0 if successful, EOF if no requests were left in this 'msg',
4420  * otherwise an OFPERR_* value. */
4421 int
4422 ofputil_decode_flow_monitor_request(struct ofputil_flow_monitor_request *rq,
4423                                     struct ofpbuf *msg)
4424 {
4425     struct nx_flow_monitor_request *nfmr;
4426     uint16_t flags;
4427
4428     if (!msg->l2) {
4429         msg->l2 = msg->data;
4430         ofpraw_pull_assert(msg);
4431     }
4432
4433     if (!msg->size) {
4434         return EOF;
4435     }
4436
4437     nfmr = ofpbuf_try_pull(msg, sizeof *nfmr);
4438     if (!nfmr) {
4439         VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR request has %zu "
4440                      "leftover bytes at end", msg->size);
4441         return OFPERR_OFPBRC_BAD_LEN;
4442     }
4443
4444     flags = ntohs(nfmr->flags);
4445     if (!(flags & (NXFMF_ADD | NXFMF_DELETE | NXFMF_MODIFY))
4446         || flags & ~(NXFMF_INITIAL | NXFMF_ADD | NXFMF_DELETE
4447                      | NXFMF_MODIFY | NXFMF_ACTIONS | NXFMF_OWN)) {
4448         VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR has bad flags %#"PRIx16,
4449                      flags);
4450         return OFPERR_NXBRC_FM_BAD_FLAGS;
4451     }
4452
4453     if (!is_all_zeros(nfmr->zeros, sizeof nfmr->zeros)) {
4454         return OFPERR_NXBRC_MUST_BE_ZERO;
4455     }
4456
4457     rq->id = ntohl(nfmr->id);
4458     rq->flags = flags;
4459     rq->out_port = u16_to_ofp(ntohs(nfmr->out_port));
4460     rq->table_id = nfmr->table_id;
4461
4462     return nx_pull_match(msg, ntohs(nfmr->match_len), &rq->match, NULL, NULL);
4463 }
4464
4465 void
4466 ofputil_append_flow_monitor_request(
4467     const struct ofputil_flow_monitor_request *rq, struct ofpbuf *msg)
4468 {
4469     struct nx_flow_monitor_request *nfmr;
4470     size_t start_ofs;
4471     int match_len;
4472
4473     if (!msg->size) {
4474         ofpraw_put(OFPRAW_NXST_FLOW_MONITOR_REQUEST, OFP10_VERSION, msg);
4475     }
4476
4477     start_ofs = msg->size;
4478     ofpbuf_put_zeros(msg, sizeof *nfmr);
4479     match_len = nx_put_match(msg, &rq->match, htonll(0), htonll(0));
4480
4481     nfmr = ofpbuf_at_assert(msg, start_ofs, sizeof *nfmr);
4482     nfmr->id = htonl(rq->id);
4483     nfmr->flags = htons(rq->flags);
4484     nfmr->out_port = htons(ofp_to_u16(rq->out_port));
4485     nfmr->match_len = htons(match_len);
4486     nfmr->table_id = rq->table_id;
4487 }
4488
4489 /* Converts an NXST_FLOW_MONITOR reply (also known as a flow update) in 'msg'
4490  * into an abstract ofputil_flow_update in 'update'.  The caller must have
4491  * initialized update->match to point to space allocated for a match.
4492  *
4493  * Uses 'ofpacts' to store the abstract OFPACT_* version of the update's
4494  * actions (except for NXFME_ABBREV, which never includes actions).  The caller
4495  * must initialize 'ofpacts' and retains ownership of it.  'update->ofpacts'
4496  * will point into the 'ofpacts' buffer.
4497  *
4498  * Multiple flow updates can be packed into a single OpenFlow message.  Calling
4499  * this function multiple times for a single 'msg' iterates through the
4500  * updates.  The caller must initially leave 'msg''s layer pointers null and
4501  * not modify them between calls.
4502  *
4503  * Returns 0 if successful, EOF if no updates were left in this 'msg',
4504  * otherwise an OFPERR_* value. */
4505 int
4506 ofputil_decode_flow_update(struct ofputil_flow_update *update,
4507                            struct ofpbuf *msg, struct ofpbuf *ofpacts)
4508 {
4509     struct nx_flow_update_header *nfuh;
4510     unsigned int length;
4511     struct ofp_header *oh;
4512
4513     if (!msg->l2) {
4514         msg->l2 = msg->data;
4515         ofpraw_pull_assert(msg);
4516     }
4517
4518     if (!msg->size) {
4519         return EOF;
4520     }
4521
4522     if (msg->size < sizeof(struct nx_flow_update_header)) {
4523         goto bad_len;
4524     }
4525
4526     oh = msg->l2;
4527
4528     nfuh = msg->data;
4529     update->event = ntohs(nfuh->event);
4530     length = ntohs(nfuh->length);
4531     if (length > msg->size || length % 8) {
4532         goto bad_len;
4533     }
4534
4535     if (update->event == NXFME_ABBREV) {
4536         struct nx_flow_update_abbrev *nfua;
4537
4538         if (length != sizeof *nfua) {
4539             goto bad_len;
4540         }
4541
4542         nfua = ofpbuf_pull(msg, sizeof *nfua);
4543         update->xid = nfua->xid;
4544         return 0;
4545     } else if (update->event == NXFME_ADDED
4546                || update->event == NXFME_DELETED
4547                || update->event == NXFME_MODIFIED) {
4548         struct nx_flow_update_full *nfuf;
4549         unsigned int actions_len;
4550         unsigned int match_len;
4551         enum ofperr error;
4552
4553         if (length < sizeof *nfuf) {
4554             goto bad_len;
4555         }
4556
4557         nfuf = ofpbuf_pull(msg, sizeof *nfuf);
4558         match_len = ntohs(nfuf->match_len);
4559         if (sizeof *nfuf + match_len > length) {
4560             goto bad_len;
4561         }
4562
4563         update->reason = ntohs(nfuf->reason);
4564         update->idle_timeout = ntohs(nfuf->idle_timeout);
4565         update->hard_timeout = ntohs(nfuf->hard_timeout);
4566         update->table_id = nfuf->table_id;
4567         update->cookie = nfuf->cookie;
4568         update->priority = ntohs(nfuf->priority);
4569
4570         error = nx_pull_match(msg, match_len, update->match, NULL, NULL);
4571         if (error) {
4572             return error;
4573         }
4574
4575         actions_len = length - sizeof *nfuf - ROUND_UP(match_len, 8);
4576         error = ofpacts_pull_openflow_actions(msg, actions_len, oh->version,
4577                                               ofpacts);
4578         if (error) {
4579             return error;
4580         }
4581
4582         update->ofpacts = ofpacts->data;
4583         update->ofpacts_len = ofpacts->size;
4584         return 0;
4585     } else {
4586         VLOG_WARN_RL(&bad_ofmsg_rl,
4587                      "NXST_FLOW_MONITOR reply has bad event %"PRIu16,
4588                      ntohs(nfuh->event));
4589         return OFPERR_NXBRC_FM_BAD_EVENT;
4590     }
4591
4592 bad_len:
4593     VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR reply has %zu "
4594                  "leftover bytes at end", msg->size);
4595     return OFPERR_OFPBRC_BAD_LEN;
4596 }
4597
4598 uint32_t
4599 ofputil_decode_flow_monitor_cancel(const struct ofp_header *oh)
4600 {
4601     const struct nx_flow_monitor_cancel *cancel = ofpmsg_body(oh);
4602
4603     return ntohl(cancel->id);
4604 }
4605
4606 struct ofpbuf *
4607 ofputil_encode_flow_monitor_cancel(uint32_t id)
4608 {
4609     struct nx_flow_monitor_cancel *nfmc;
4610     struct ofpbuf *msg;
4611
4612     msg = ofpraw_alloc(OFPRAW_NXT_FLOW_MONITOR_CANCEL, OFP10_VERSION, 0);
4613     nfmc = ofpbuf_put_uninit(msg, sizeof *nfmc);
4614     nfmc->id = htonl(id);
4615     return msg;
4616 }
4617
4618 void
4619 ofputil_start_flow_update(struct list *replies)
4620 {
4621     struct ofpbuf *msg;
4622
4623     msg = ofpraw_alloc_xid(OFPRAW_NXST_FLOW_MONITOR_REPLY, OFP10_VERSION,
4624                            htonl(0), 1024);
4625
4626     list_init(replies);
4627     list_push_back(replies, &msg->list_node);
4628 }
4629
4630 void
4631 ofputil_append_flow_update(const struct ofputil_flow_update *update,
4632                            struct list *replies)
4633 {
4634     struct nx_flow_update_header *nfuh;
4635     struct ofpbuf *msg;
4636     size_t start_ofs;
4637     enum ofp_version version;
4638
4639     msg = ofpbuf_from_list(list_back(replies));
4640     start_ofs = msg->size;
4641     version = ((struct ofp_header *)msg->l2)->version;
4642
4643     if (update->event == NXFME_ABBREV) {
4644         struct nx_flow_update_abbrev *nfua;
4645
4646         nfua = ofpbuf_put_zeros(msg, sizeof *nfua);
4647         nfua->xid = update->xid;
4648     } else {
4649         struct nx_flow_update_full *nfuf;
4650         int match_len;
4651
4652         ofpbuf_put_zeros(msg, sizeof *nfuf);
4653         match_len = nx_put_match(msg, update->match, htonll(0), htonll(0));
4654         ofpacts_put_openflow_actions(update->ofpacts, update->ofpacts_len, msg,
4655                                      version);
4656         nfuf = ofpbuf_at_assert(msg, start_ofs, sizeof *nfuf);
4657         nfuf->reason = htons(update->reason);
4658         nfuf->priority = htons(update->priority);
4659         nfuf->idle_timeout = htons(update->idle_timeout);
4660         nfuf->hard_timeout = htons(update->hard_timeout);
4661         nfuf->match_len = htons(match_len);
4662         nfuf->table_id = update->table_id;
4663         nfuf->cookie = update->cookie;
4664     }
4665
4666     nfuh = ofpbuf_at_assert(msg, start_ofs, sizeof *nfuh);
4667     nfuh->length = htons(msg->size - start_ofs);
4668     nfuh->event = htons(update->event);
4669
4670     ofpmp_postappend(replies, start_ofs);
4671 }
4672 \f
4673 struct ofpbuf *
4674 ofputil_encode_packet_out(const struct ofputil_packet_out *po,
4675                           enum ofputil_protocol protocol)
4676 {
4677     enum ofp_version ofp_version = ofputil_protocol_to_ofp_version(protocol);
4678     struct ofpbuf *msg;
4679     size_t size;
4680
4681     size = po->ofpacts_len;
4682     if (po->buffer_id == UINT32_MAX) {
4683         size += po->packet_len;
4684     }
4685
4686     switch (ofp_version) {
4687     case OFP10_VERSION: {
4688         struct ofp10_packet_out *opo;
4689         size_t actions_ofs;
4690
4691         msg = ofpraw_alloc(OFPRAW_OFPT10_PACKET_OUT, OFP10_VERSION, size);
4692         ofpbuf_put_zeros(msg, sizeof *opo);
4693         actions_ofs = msg->size;
4694         ofpacts_put_openflow_actions(po->ofpacts, po->ofpacts_len, msg,
4695                                      ofp_version);
4696
4697         opo = msg->l3;
4698         opo->buffer_id = htonl(po->buffer_id);
4699         opo->in_port = htons(ofp_to_u16(po->in_port));
4700         opo->actions_len = htons(msg->size - actions_ofs);
4701         break;
4702     }
4703
4704     case OFP11_VERSION:
4705     case OFP12_VERSION:
4706     case OFP13_VERSION: {
4707         struct ofp11_packet_out *opo;
4708         size_t len;
4709
4710         msg = ofpraw_alloc(OFPRAW_OFPT11_PACKET_OUT, ofp_version, size);
4711         ofpbuf_put_zeros(msg, sizeof *opo);
4712         len = ofpacts_put_openflow_actions(po->ofpacts, po->ofpacts_len, msg,
4713                                            ofp_version);
4714         opo = msg->l3;
4715         opo->buffer_id = htonl(po->buffer_id);
4716         opo->in_port = ofputil_port_to_ofp11(po->in_port);
4717         opo->actions_len = htons(len);
4718         break;
4719     }
4720
4721     default:
4722         NOT_REACHED();
4723     }
4724
4725     if (po->buffer_id == UINT32_MAX) {
4726         ofpbuf_put(msg, po->packet, po->packet_len);
4727     }
4728
4729     ofpmsg_update_length(msg);
4730
4731     return msg;
4732 }
4733 \f
4734 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
4735 struct ofpbuf *
4736 make_echo_request(enum ofp_version ofp_version)
4737 {
4738     return ofpraw_alloc_xid(OFPRAW_OFPT_ECHO_REQUEST, ofp_version,
4739                             htonl(0), 0);
4740 }
4741
4742 /* Creates and returns an OFPT_ECHO_REPLY message matching the
4743  * OFPT_ECHO_REQUEST message in 'rq'. */
4744 struct ofpbuf *
4745 make_echo_reply(const struct ofp_header *rq)
4746 {
4747     struct ofpbuf rq_buf;
4748     struct ofpbuf *reply;
4749
4750     ofpbuf_use_const(&rq_buf, rq, ntohs(rq->length));
4751     ofpraw_pull_assert(&rq_buf);
4752
4753     reply = ofpraw_alloc_reply(OFPRAW_OFPT_ECHO_REPLY, rq, rq_buf.size);
4754     ofpbuf_put(reply, rq_buf.data, rq_buf.size);
4755     return reply;
4756 }
4757
4758 struct ofpbuf *
4759 ofputil_encode_barrier_request(enum ofp_version ofp_version)
4760 {
4761     enum ofpraw type;
4762
4763     switch (ofp_version) {
4764     case OFP13_VERSION:
4765     case OFP12_VERSION:
4766     case OFP11_VERSION:
4767         type = OFPRAW_OFPT11_BARRIER_REQUEST;
4768         break;
4769
4770     case OFP10_VERSION:
4771         type = OFPRAW_OFPT10_BARRIER_REQUEST;
4772         break;
4773
4774     default:
4775         NOT_REACHED();
4776     }
4777
4778     return ofpraw_alloc(type, ofp_version, 0);
4779 }
4780
4781 const char *
4782 ofputil_frag_handling_to_string(enum ofp_config_flags flags)
4783 {
4784     switch (flags & OFPC_FRAG_MASK) {
4785     case OFPC_FRAG_NORMAL:   return "normal";
4786     case OFPC_FRAG_DROP:     return "drop";
4787     case OFPC_FRAG_REASM:    return "reassemble";
4788     case OFPC_FRAG_NX_MATCH: return "nx-match";
4789     }
4790
4791     NOT_REACHED();
4792 }
4793
4794 bool
4795 ofputil_frag_handling_from_string(const char *s, enum ofp_config_flags *flags)
4796 {
4797     if (!strcasecmp(s, "normal")) {
4798         *flags = OFPC_FRAG_NORMAL;
4799     } else if (!strcasecmp(s, "drop")) {
4800         *flags = OFPC_FRAG_DROP;
4801     } else if (!strcasecmp(s, "reassemble")) {
4802         *flags = OFPC_FRAG_REASM;
4803     } else if (!strcasecmp(s, "nx-match")) {
4804         *flags = OFPC_FRAG_NX_MATCH;
4805     } else {
4806         return false;
4807     }
4808     return true;
4809 }
4810
4811 /* Converts the OpenFlow 1.1+ port number 'ofp11_port' into an OpenFlow 1.0
4812  * port number and stores the latter in '*ofp10_port', for the purpose of
4813  * decoding OpenFlow 1.1+ protocol messages.  Returns 0 if successful,
4814  * otherwise an OFPERR_* number.  On error, stores OFPP_NONE in '*ofp10_port'.
4815  *
4816  * See the definition of OFP11_MAX for an explanation of the mapping. */
4817 enum ofperr
4818 ofputil_port_from_ofp11(ovs_be32 ofp11_port, ofp_port_t *ofp10_port)
4819 {
4820     uint32_t ofp11_port_h = ntohl(ofp11_port);
4821
4822     if (ofp11_port_h < ofp_to_u16(OFPP_MAX)) {
4823         *ofp10_port = u16_to_ofp(ofp11_port_h);
4824         return 0;
4825     } else if (ofp11_port_h >= ofp11_to_u32(OFPP11_MAX)) {
4826         *ofp10_port = u16_to_ofp(ofp11_port_h - OFPP11_OFFSET);
4827         return 0;
4828     } else {
4829         *ofp10_port = OFPP_NONE;
4830         VLOG_WARN_RL(&bad_ofmsg_rl, "port %"PRIu32" is outside the supported "
4831                      "range 0 through %d or 0x%"PRIx32" through 0x%"PRIx32,
4832                      ofp11_port_h, ofp_to_u16(OFPP_MAX) - 1,
4833                      ofp11_to_u32(OFPP11_MAX), UINT32_MAX);
4834         return OFPERR_OFPBAC_BAD_OUT_PORT;
4835     }
4836 }
4837
4838 /* Returns the OpenFlow 1.1+ port number equivalent to the OpenFlow 1.0 port
4839  * number 'ofp10_port', for encoding OpenFlow 1.1+ protocol messages.
4840  *
4841  * See the definition of OFP11_MAX for an explanation of the mapping. */
4842 ovs_be32
4843 ofputil_port_to_ofp11(ofp_port_t ofp10_port)
4844 {
4845     return htonl(ofp_to_u16(ofp10_port) < ofp_to_u16(OFPP_MAX)
4846                  ? ofp_to_u16(ofp10_port)
4847                  : ofp_to_u16(ofp10_port) + OFPP11_OFFSET);
4848 }
4849
4850 /* Checks that 'port' is a valid output port for the OFPAT10_OUTPUT action, given
4851  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
4852  * 'port' is valid, otherwise an OpenFlow return code. */
4853 enum ofperr
4854 ofputil_check_output_port(ofp_port_t port, ofp_port_t max_ports)
4855 {
4856     switch (port) {
4857     case OFPP_IN_PORT:
4858     case OFPP_TABLE:
4859     case OFPP_NORMAL:
4860     case OFPP_FLOOD:
4861     case OFPP_ALL:
4862     case OFPP_CONTROLLER:
4863     case OFPP_NONE:
4864     case OFPP_LOCAL:
4865         return 0;
4866
4867     default:
4868         if (ofp_to_u16(port) < ofp_to_u16(max_ports)) {
4869             return 0;
4870         }
4871         return OFPERR_OFPBAC_BAD_OUT_PORT;
4872     }
4873 }
4874
4875 #define OFPUTIL_NAMED_PORTS                     \
4876         OFPUTIL_NAMED_PORT(IN_PORT)             \
4877         OFPUTIL_NAMED_PORT(TABLE)               \
4878         OFPUTIL_NAMED_PORT(NORMAL)              \
4879         OFPUTIL_NAMED_PORT(FLOOD)               \
4880         OFPUTIL_NAMED_PORT(ALL)                 \
4881         OFPUTIL_NAMED_PORT(CONTROLLER)          \
4882         OFPUTIL_NAMED_PORT(LOCAL)               \
4883         OFPUTIL_NAMED_PORT(ANY)
4884
4885 /* For backwards compatibility, so that "none" is recognized as OFPP_ANY */
4886 #define OFPUTIL_NAMED_PORTS_WITH_NONE           \
4887         OFPUTIL_NAMED_PORTS                     \
4888         OFPUTIL_NAMED_PORT(NONE)
4889
4890 /* Stores the port number represented by 's' into '*portp'.  's' may be an
4891  * integer or, for reserved ports, the standard OpenFlow name for the port
4892  * (e.g. "LOCAL").
4893  *
4894  * Returns true if successful, false if 's' is not a valid OpenFlow port number
4895  * or name.  The caller should issue an error message in this case, because
4896  * this function usually does not.  (This gives the caller an opportunity to
4897  * look up the port name another way, e.g. by contacting the switch and listing
4898  * the names of all its ports).
4899  *
4900  * This function accepts OpenFlow 1.0 port numbers.  It also accepts a subset
4901  * of OpenFlow 1.1+ port numbers, mapping those port numbers into the 16-bit
4902  * range as described in include/openflow/openflow-1.1.h. */
4903 bool
4904 ofputil_port_from_string(const char *s, ofp_port_t *portp)
4905 {
4906     uint32_t port32;
4907
4908     *portp = 0;
4909     if (str_to_uint(s, 10, &port32)) {
4910         if (port32 < ofp_to_u16(OFPP_MAX)) {
4911             /* Pass. */
4912         } else if (port32 < ofp_to_u16(OFPP_FIRST_RESV)) {
4913             VLOG_WARN("port %u is a reserved OF1.0 port number that will "
4914                       "be translated to %u when talking to an OF1.1 or "
4915                       "later controller", port32, port32 + OFPP11_OFFSET);
4916         } else if (port32 <= ofp_to_u16(OFPP_LAST_RESV)) {
4917             char name[OFP_MAX_PORT_NAME_LEN];
4918
4919             ofputil_port_to_string(u16_to_ofp(port32), name, sizeof name);
4920             VLOG_WARN_ONCE("referring to port %s as %"PRIu32" is deprecated "
4921                            "for compatibility with OpenFlow 1.1 and later",
4922                            name, port32);
4923         } else if (port32 < ofp11_to_u32(OFPP11_MAX)) {
4924             VLOG_WARN("port %u is outside the supported range 0 through "
4925                       "%"PRIx16" or 0x%x through 0x%"PRIx32, port32,
4926                       UINT16_MAX, ofp11_to_u32(OFPP11_MAX), UINT32_MAX);
4927             return false;
4928         } else {
4929             port32 -= OFPP11_OFFSET;
4930         }
4931
4932         *portp = u16_to_ofp(port32);
4933         return true;
4934     } else {
4935         struct pair {
4936             const char *name;
4937             ofp_port_t value;
4938         };
4939         static const struct pair pairs[] = {
4940 #define OFPUTIL_NAMED_PORT(NAME) {#NAME, OFPP_##NAME},
4941             OFPUTIL_NAMED_PORTS_WITH_NONE
4942 #undef OFPUTIL_NAMED_PORT
4943         };
4944         const struct pair *p;
4945
4946         for (p = pairs; p < &pairs[ARRAY_SIZE(pairs)]; p++) {
4947             if (!strcasecmp(s, p->name)) {
4948                 *portp = p->value;
4949                 return true;
4950             }
4951         }
4952         return false;
4953     }
4954 }
4955
4956 /* Appends to 's' a string representation of the OpenFlow port number 'port'.
4957  * Most ports' string representation is just the port number, but for special
4958  * ports, e.g. OFPP_LOCAL, it is the name, e.g. "LOCAL". */
4959 void
4960 ofputil_format_port(ofp_port_t port, struct ds *s)
4961 {
4962     char name[OFP_MAX_PORT_NAME_LEN];
4963
4964     ofputil_port_to_string(port, name, sizeof name);
4965     ds_put_cstr(s, name);
4966 }
4967
4968 /* Puts in the 'bufsize' byte in 'namebuf' a null-terminated string
4969  * representation of OpenFlow port number 'port'.  Most ports are represented
4970  * as just the port number, but special ports, e.g. OFPP_LOCAL, are represented
4971  * by name, e.g. "LOCAL". */
4972 void
4973 ofputil_port_to_string(ofp_port_t port,
4974                        char namebuf[OFP_MAX_PORT_NAME_LEN], size_t bufsize)
4975 {
4976     switch (port) {
4977 #define OFPUTIL_NAMED_PORT(NAME)                        \
4978         case OFPP_##NAME:                               \
4979             ovs_strlcpy(namebuf, #NAME, bufsize);       \
4980             break;
4981         OFPUTIL_NAMED_PORTS
4982 #undef OFPUTIL_NAMED_PORT
4983
4984     default:
4985         snprintf(namebuf, bufsize, "%"PRIu16, port);
4986         break;
4987     }
4988 }
4989
4990 /* Stores the group id represented by 's' into '*group_idp'.  's' may be an
4991  * integer or, for reserved group IDs, the standard OpenFlow name for the group
4992  * (either "ANY" or "ALL").
4993  *
4994  * Returns true if successful, false if 's' is not a valid OpenFlow group ID or
4995  * name. */
4996 bool
4997 ofputil_group_from_string(const char *s, uint32_t *group_idp)
4998 {
4999     if (!strcasecmp(s, "any")) {
5000         *group_idp = OFPG11_ANY;
5001     } else if (!strcasecmp(s, "all")) {
5002         *group_idp = OFPG11_ALL;
5003     } else if (!str_to_uint(s, 10, group_idp)) {
5004         VLOG_WARN("%s is not a valid group ID.  (Valid group IDs are "
5005                   "32-bit nonnegative integers or the keywords ANY or "
5006                   "ALL.)", s);
5007         return false;
5008     }
5009
5010     return true;
5011 }
5012
5013 /* Appends to 's' a string representation of the OpenFlow group ID 'group_id'.
5014  * Most groups' string representation is just the number, but for special
5015  * groups, e.g. OFPG11_ALL, it is the name, e.g. "ALL". */
5016 void
5017 ofputil_format_group(uint32_t group_id, struct ds *s)
5018 {
5019     char name[MAX_GROUP_NAME_LEN];
5020
5021     ofputil_group_to_string(group_id, name, sizeof name);
5022     ds_put_cstr(s, name);
5023 }
5024
5025
5026 /* Puts in the 'bufsize' byte in 'namebuf' a null-terminated string
5027  * representation of OpenFlow group ID 'group_id'.  Most group are represented
5028  * as just their number, but special groups, e.g. OFPG11_ALL, are represented
5029  * by name, e.g. "ALL". */
5030 void
5031 ofputil_group_to_string(uint32_t group_id,
5032                         char namebuf[MAX_GROUP_NAME_LEN + 1], size_t bufsize)
5033 {
5034     switch (group_id) {
5035     case OFPG11_ALL:
5036         ovs_strlcpy(namebuf, "ALL", bufsize);
5037         break;
5038
5039     case OFPG11_ANY:
5040         ovs_strlcpy(namebuf, "ANY", bufsize);
5041         break;
5042
5043     default:
5044         snprintf(namebuf, bufsize, "%"PRIu32, group_id);
5045         break;
5046     }
5047 }
5048
5049 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
5050  * 'ofp_version', tries to pull the first element from the array.  If
5051  * successful, initializes '*pp' with an abstract representation of the
5052  * port and returns 0.  If no ports remain to be decoded, returns EOF.
5053  * On an error, returns a positive OFPERR_* value. */
5054 int
5055 ofputil_pull_phy_port(enum ofp_version ofp_version, struct ofpbuf *b,
5056                       struct ofputil_phy_port *pp)
5057 {
5058     switch (ofp_version) {
5059     case OFP10_VERSION: {
5060         const struct ofp10_phy_port *opp = ofpbuf_try_pull(b, sizeof *opp);
5061         return opp ? ofputil_decode_ofp10_phy_port(pp, opp) : EOF;
5062     }
5063     case OFP11_VERSION:
5064     case OFP12_VERSION:
5065     case OFP13_VERSION: {
5066         const struct ofp11_port *op = ofpbuf_try_pull(b, sizeof *op);
5067         return op ? ofputil_decode_ofp11_port(pp, op) : EOF;
5068     }
5069     default:
5070         NOT_REACHED();
5071     }
5072 }
5073
5074 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
5075  * 'ofp_version', returns the number of elements. */
5076 size_t ofputil_count_phy_ports(uint8_t ofp_version, struct ofpbuf *b)
5077 {
5078     return b->size / ofputil_get_phy_port_size(ofp_version);
5079 }
5080
5081 /* ofp-util.def lists the mapping from names to action. */
5082 static const char *const names[OFPUTIL_N_ACTIONS] = {
5083     NULL,
5084 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)             NAME,
5085 #define OFPAT11_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) NAME,
5086 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)   NAME,
5087 #include "ofp-util.def"
5088 };
5089
5090 /* Returns the 'enum ofputil_action_code' corresponding to 'name' (e.g. if
5091  * 'name' is "output" then the return value is OFPUTIL_OFPAT10_OUTPUT), or -1
5092  * if 'name' is not the name of any action. */
5093 int
5094 ofputil_action_code_from_name(const char *name)
5095 {
5096     const char *const *p;
5097
5098     for (p = names; p < &names[ARRAY_SIZE(names)]; p++) {
5099         if (*p && !strcasecmp(name, *p)) {
5100             return p - names;
5101         }
5102     }
5103     return -1;
5104 }
5105
5106 /* Returns name corresponding to the 'enum ofputil_action_code',
5107  * or "Unkonwn action", if the name is not available. */
5108 const char *
5109 ofputil_action_name_from_code(enum ofputil_action_code code)
5110 {
5111     return code < (int)OFPUTIL_N_ACTIONS && names[code] ? names[code]
5112         : "Unknown action";
5113 }
5114
5115 /* Appends an action of the type specified by 'code' to 'buf' and returns the
5116  * action.  Initializes the parts of 'action' that identify it as having type
5117  * <ENUM> and length 'sizeof *action' and zeros the rest.  For actions that
5118  * have variable length, the length used and cleared is that of struct
5119  * <STRUCT>.  */
5120 void *
5121 ofputil_put_action(enum ofputil_action_code code, struct ofpbuf *buf)
5122 {
5123     switch (code) {
5124     case OFPUTIL_ACTION_INVALID:
5125         NOT_REACHED();
5126
5127 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                  \
5128     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
5129 #define OFPAT11_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)      \
5130     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
5131 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)        \
5132     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
5133 #include "ofp-util.def"
5134     }
5135     NOT_REACHED();
5136 }
5137
5138 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                        \
5139     void                                                        \
5140     ofputil_init_##ENUM(struct STRUCT *s)                       \
5141     {                                                           \
5142         memset(s, 0, sizeof *s);                                \
5143         s->type = htons(ENUM);                                  \
5144         s->len = htons(sizeof *s);                              \
5145     }                                                           \
5146                                                                 \
5147     struct STRUCT *                                             \
5148     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
5149     {                                                           \
5150         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
5151         ofputil_init_##ENUM(s);                                 \
5152         return s;                                               \
5153     }
5154 #define OFPAT11_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) \
5155     OFPAT10_ACTION(ENUM, STRUCT, NAME)
5156 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)            \
5157     void                                                        \
5158     ofputil_init_##ENUM(struct STRUCT *s)                       \
5159     {                                                           \
5160         memset(s, 0, sizeof *s);                                \
5161         s->type = htons(OFPAT10_VENDOR);                        \
5162         s->len = htons(sizeof *s);                              \
5163         s->vendor = htonl(NX_VENDOR_ID);                        \
5164         s->subtype = htons(ENUM);                               \
5165     }                                                           \
5166                                                                 \
5167     struct STRUCT *                                             \
5168     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
5169     {                                                           \
5170         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
5171         ofputil_init_##ENUM(s);                                 \
5172         return s;                                               \
5173     }
5174 #include "ofp-util.def"
5175
5176 static void
5177 ofputil_normalize_match__(struct match *match, bool may_log)
5178 {
5179     enum {
5180         MAY_NW_ADDR     = 1 << 0, /* nw_src, nw_dst */
5181         MAY_TP_ADDR     = 1 << 1, /* tp_src, tp_dst */
5182         MAY_NW_PROTO    = 1 << 2, /* nw_proto */
5183         MAY_IPVx        = 1 << 3, /* tos, frag, ttl */
5184         MAY_ARP_SHA     = 1 << 4, /* arp_sha */
5185         MAY_ARP_THA     = 1 << 5, /* arp_tha */
5186         MAY_IPV6        = 1 << 6, /* ipv6_src, ipv6_dst, ipv6_label */
5187         MAY_ND_TARGET   = 1 << 7, /* nd_target */
5188         MAY_MPLS        = 1 << 8, /* mpls label and tc */
5189     } may_match;
5190
5191     struct flow_wildcards wc;
5192
5193     /* Figure out what fields may be matched. */
5194     if (match->flow.dl_type == htons(ETH_TYPE_IP)) {
5195         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_NW_ADDR;
5196         if (match->flow.nw_proto == IPPROTO_TCP ||
5197             match->flow.nw_proto == IPPROTO_UDP ||
5198             match->flow.nw_proto == IPPROTO_SCTP ||
5199             match->flow.nw_proto == IPPROTO_ICMP) {
5200             may_match |= MAY_TP_ADDR;
5201         }
5202     } else if (match->flow.dl_type == htons(ETH_TYPE_IPV6)) {
5203         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_IPV6;
5204         if (match->flow.nw_proto == IPPROTO_TCP ||
5205             match->flow.nw_proto == IPPROTO_UDP ||
5206             match->flow.nw_proto == IPPROTO_SCTP) {
5207             may_match |= MAY_TP_ADDR;
5208         } else if (match->flow.nw_proto == IPPROTO_ICMPV6) {
5209             may_match |= MAY_TP_ADDR;
5210             if (match->flow.tp_src == htons(ND_NEIGHBOR_SOLICIT)) {
5211                 may_match |= MAY_ND_TARGET | MAY_ARP_SHA;
5212             } else if (match->flow.tp_src == htons(ND_NEIGHBOR_ADVERT)) {
5213                 may_match |= MAY_ND_TARGET | MAY_ARP_THA;
5214             }
5215         }
5216     } else if (match->flow.dl_type == htons(ETH_TYPE_ARP) ||
5217                match->flow.dl_type == htons(ETH_TYPE_RARP)) {
5218         may_match = MAY_NW_PROTO | MAY_NW_ADDR | MAY_ARP_SHA | MAY_ARP_THA;
5219     } else if (eth_type_mpls(match->flow.dl_type)) {
5220         may_match = MAY_MPLS;
5221     } else {
5222         may_match = 0;
5223     }
5224
5225     /* Clear the fields that may not be matched. */
5226     wc = match->wc;
5227     if (!(may_match & MAY_NW_ADDR)) {
5228         wc.masks.nw_src = wc.masks.nw_dst = htonl(0);
5229     }
5230     if (!(may_match & MAY_TP_ADDR)) {
5231         wc.masks.tp_src = wc.masks.tp_dst = htons(0);
5232     }
5233     if (!(may_match & MAY_NW_PROTO)) {
5234         wc.masks.nw_proto = 0;
5235     }
5236     if (!(may_match & MAY_IPVx)) {
5237         wc.masks.nw_tos = 0;
5238         wc.masks.nw_ttl = 0;
5239     }
5240     if (!(may_match & MAY_ARP_SHA)) {
5241         memset(wc.masks.arp_sha, 0, ETH_ADDR_LEN);
5242     }
5243     if (!(may_match & MAY_ARP_THA)) {
5244         memset(wc.masks.arp_tha, 0, ETH_ADDR_LEN);
5245     }
5246     if (!(may_match & MAY_IPV6)) {
5247         wc.masks.ipv6_src = wc.masks.ipv6_dst = in6addr_any;
5248         wc.masks.ipv6_label = htonl(0);
5249     }
5250     if (!(may_match & MAY_ND_TARGET)) {
5251         wc.masks.nd_target = in6addr_any;
5252     }
5253     if (!(may_match & MAY_MPLS)) {
5254         wc.masks.mpls_lse = htonl(0);
5255     }
5256
5257     /* Log any changes. */
5258     if (!flow_wildcards_equal(&wc, &match->wc)) {
5259         bool log = may_log && !VLOG_DROP_INFO(&bad_ofmsg_rl);
5260         char *pre = log ? match_to_string(match, OFP_DEFAULT_PRIORITY) : NULL;
5261
5262         match->wc = wc;
5263         match_zero_wildcarded_fields(match);
5264
5265         if (log) {
5266             char *post = match_to_string(match, OFP_DEFAULT_PRIORITY);
5267             VLOG_INFO("normalization changed ofp_match, details:");
5268             VLOG_INFO(" pre: %s", pre);
5269             VLOG_INFO("post: %s", post);
5270             free(pre);
5271             free(post);
5272         }
5273     }
5274 }
5275
5276 /* "Normalizes" the wildcards in 'match'.  That means:
5277  *
5278  *    1. If the type of level N is known, then only the valid fields for that
5279  *       level may be specified.  For example, ARP does not have a TOS field,
5280  *       so nw_tos must be wildcarded if 'match' specifies an ARP flow.
5281  *       Similarly, IPv4 does not have any IPv6 addresses, so ipv6_src and
5282  *       ipv6_dst (and other fields) must be wildcarded if 'match' specifies an
5283  *       IPv4 flow.
5284  *
5285  *    2. If the type of level N is not known (or not understood by Open
5286  *       vSwitch), then no fields at all for that level may be specified.  For
5287  *       example, Open vSwitch does not understand SCTP, an L4 protocol, so the
5288  *       L4 fields tp_src and tp_dst must be wildcarded if 'match' specifies an
5289  *       SCTP flow.
5290  *
5291  * If this function changes 'match', it logs a rate-limited informational
5292  * message. */
5293 void
5294 ofputil_normalize_match(struct match *match)
5295 {
5296     ofputil_normalize_match__(match, true);
5297 }
5298
5299 /* Same as ofputil_normalize_match() without the logging.  Thus, this function
5300  * is suitable for a program's internal use, whereas ofputil_normalize_match()
5301  * sense for use on flows received from elsewhere (so that a bug in the program
5302  * that sent them can be reported and corrected). */
5303 void
5304 ofputil_normalize_match_quiet(struct match *match)
5305 {
5306     ofputil_normalize_match__(match, false);
5307 }
5308
5309 /* Parses a key or a key-value pair from '*stringp'.
5310  *
5311  * On success: Stores the key into '*keyp'.  Stores the value, if present, into
5312  * '*valuep', otherwise an empty string.  Advances '*stringp' past the end of
5313  * the key-value pair, preparing it for another call.  '*keyp' and '*valuep'
5314  * are substrings of '*stringp' created by replacing some of its bytes by null
5315  * terminators.  Returns true.
5316  *
5317  * If '*stringp' is just white space or commas, sets '*keyp' and '*valuep' to
5318  * NULL and returns false. */
5319 bool
5320 ofputil_parse_key_value(char **stringp, char **keyp, char **valuep)
5321 {
5322     char *pos, *key, *value;
5323     size_t key_len;
5324
5325     pos = *stringp;
5326     pos += strspn(pos, ", \t\r\n");
5327     if (*pos == '\0') {
5328         *keyp = *valuep = NULL;
5329         return false;
5330     }
5331
5332     key = pos;
5333     key_len = strcspn(pos, ":=(, \t\r\n");
5334     if (key[key_len] == ':' || key[key_len] == '=') {
5335         /* The value can be separated by a colon. */
5336         size_t value_len;
5337
5338         value = key + key_len + 1;
5339         value_len = strcspn(value, ", \t\r\n");
5340         pos = value + value_len + (value[value_len] != '\0');
5341         value[value_len] = '\0';
5342     } else if (key[key_len] == '(') {
5343         /* The value can be surrounded by balanced parentheses.  The outermost
5344          * set of parentheses is removed. */
5345         int level = 1;
5346         size_t value_len;
5347
5348         value = key + key_len + 1;
5349         for (value_len = 0; level > 0; value_len++) {
5350             switch (value[value_len]) {
5351             case '\0':
5352                 level = 0;
5353                 break;
5354
5355             case '(':
5356                 level++;
5357                 break;
5358
5359             case ')':
5360                 level--;
5361                 break;
5362             }
5363         }
5364         value[value_len - 1] = '\0';
5365         pos = value + value_len;
5366     } else {
5367         /* There might be no value at all. */
5368         value = key + key_len;  /* Will become the empty string below. */
5369         pos = key + key_len + (key[key_len] != '\0');
5370     }
5371     key[key_len] = '\0';
5372
5373     *stringp = pos;
5374     *keyp = key;
5375     *valuep = value;
5376     return true;
5377 }
5378
5379 /* Encode a dump ports request for 'port', the encoded message
5380  * will be for Open Flow version 'ofp_version'. Returns message
5381  * as a struct ofpbuf. Returns encoded message on success, NULL on error */
5382 struct ofpbuf *
5383 ofputil_encode_dump_ports_request(enum ofp_version ofp_version, ofp_port_t port)
5384 {
5385     struct ofpbuf *request;
5386
5387     switch (ofp_version) {
5388     case OFP10_VERSION: {
5389         struct ofp10_port_stats_request *req;
5390         request = ofpraw_alloc(OFPRAW_OFPST10_PORT_REQUEST, ofp_version, 0);
5391         req = ofpbuf_put_zeros(request, sizeof *req);
5392         req->port_no = htons(ofp_to_u16(port));
5393         break;
5394     }
5395     case OFP11_VERSION:
5396     case OFP12_VERSION:
5397     case OFP13_VERSION: {
5398         struct ofp11_port_stats_request *req;
5399         request = ofpraw_alloc(OFPRAW_OFPST11_PORT_REQUEST, ofp_version, 0);
5400         req = ofpbuf_put_zeros(request, sizeof *req);
5401         req->port_no = ofputil_port_to_ofp11(port);
5402         break;
5403     }
5404     default:
5405         NOT_REACHED();
5406     }
5407
5408     return request;
5409 }
5410
5411 static void
5412 ofputil_port_stats_to_ofp10(const struct ofputil_port_stats *ops,
5413                             struct ofp10_port_stats *ps10)
5414 {
5415     ps10->port_no = htons(ofp_to_u16(ops->port_no));
5416     memset(ps10->pad, 0, sizeof ps10->pad);
5417     put_32aligned_be64(&ps10->rx_packets, htonll(ops->stats.rx_packets));
5418     put_32aligned_be64(&ps10->tx_packets, htonll(ops->stats.tx_packets));
5419     put_32aligned_be64(&ps10->rx_bytes, htonll(ops->stats.rx_bytes));
5420     put_32aligned_be64(&ps10->tx_bytes, htonll(ops->stats.tx_bytes));
5421     put_32aligned_be64(&ps10->rx_dropped, htonll(ops->stats.rx_dropped));
5422     put_32aligned_be64(&ps10->tx_dropped, htonll(ops->stats.tx_dropped));
5423     put_32aligned_be64(&ps10->rx_errors, htonll(ops->stats.rx_errors));
5424     put_32aligned_be64(&ps10->tx_errors, htonll(ops->stats.tx_errors));
5425     put_32aligned_be64(&ps10->rx_frame_err, htonll(ops->stats.rx_frame_errors));
5426     put_32aligned_be64(&ps10->rx_over_err, htonll(ops->stats.rx_over_errors));
5427     put_32aligned_be64(&ps10->rx_crc_err, htonll(ops->stats.rx_crc_errors));
5428     put_32aligned_be64(&ps10->collisions, htonll(ops->stats.collisions));
5429 }
5430
5431 static void
5432 ofputil_port_stats_to_ofp11(const struct ofputil_port_stats *ops,
5433                             struct ofp11_port_stats *ps11)
5434 {
5435     ps11->port_no = ofputil_port_to_ofp11(ops->port_no);
5436     memset(ps11->pad, 0, sizeof ps11->pad);
5437     ps11->rx_packets = htonll(ops->stats.rx_packets);
5438     ps11->tx_packets = htonll(ops->stats.tx_packets);
5439     ps11->rx_bytes = htonll(ops->stats.rx_bytes);
5440     ps11->tx_bytes = htonll(ops->stats.tx_bytes);
5441     ps11->rx_dropped = htonll(ops->stats.rx_dropped);
5442     ps11->tx_dropped = htonll(ops->stats.tx_dropped);
5443     ps11->rx_errors = htonll(ops->stats.rx_errors);
5444     ps11->tx_errors = htonll(ops->stats.tx_errors);
5445     ps11->rx_frame_err = htonll(ops->stats.rx_frame_errors);
5446     ps11->rx_over_err = htonll(ops->stats.rx_over_errors);
5447     ps11->rx_crc_err = htonll(ops->stats.rx_crc_errors);
5448     ps11->collisions = htonll(ops->stats.collisions);
5449 }
5450
5451 static void
5452 ofputil_port_stats_to_ofp13(const struct ofputil_port_stats *ops,
5453                             struct ofp13_port_stats *ps13)
5454 {
5455     ofputil_port_stats_to_ofp11(ops, &ps13->ps);
5456     ps13->duration_sec = htonl(ops->duration_sec);
5457     ps13->duration_nsec = htonl(ops->duration_nsec);
5458 }
5459
5460
5461 /* Encode a ports stat for 'ops' and append it to 'replies'. */
5462 void
5463 ofputil_append_port_stat(struct list *replies,
5464                          const struct ofputil_port_stats *ops)
5465 {
5466     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
5467     struct ofp_header *oh = msg->data;
5468
5469     switch ((enum ofp_version)oh->version) {
5470     case OFP13_VERSION: {
5471         struct ofp13_port_stats *reply = ofpmp_append(replies, sizeof *reply);
5472         ofputil_port_stats_to_ofp13(ops, reply);
5473         break;
5474     }
5475     case OFP12_VERSION:
5476     case OFP11_VERSION: {
5477         struct ofp11_port_stats *reply = ofpmp_append(replies, sizeof *reply);
5478         ofputil_port_stats_to_ofp11(ops, reply);
5479         break;
5480     }
5481
5482     case OFP10_VERSION: {
5483         struct ofp10_port_stats *reply = ofpmp_append(replies, sizeof *reply);
5484         ofputil_port_stats_to_ofp10(ops, reply);
5485         break;
5486     }
5487
5488     default:
5489         NOT_REACHED();
5490     }
5491 }
5492
5493 static enum ofperr
5494 ofputil_port_stats_from_ofp10(struct ofputil_port_stats *ops,
5495                               const struct ofp10_port_stats *ps10)
5496 {
5497     memset(ops, 0, sizeof *ops);
5498
5499     ops->port_no = u16_to_ofp(ntohs(ps10->port_no));
5500     ops->stats.rx_packets = ntohll(get_32aligned_be64(&ps10->rx_packets));
5501     ops->stats.tx_packets = ntohll(get_32aligned_be64(&ps10->tx_packets));
5502     ops->stats.rx_bytes = ntohll(get_32aligned_be64(&ps10->rx_bytes));
5503     ops->stats.tx_bytes = ntohll(get_32aligned_be64(&ps10->tx_bytes));
5504     ops->stats.rx_dropped = ntohll(get_32aligned_be64(&ps10->rx_dropped));
5505     ops->stats.tx_dropped = ntohll(get_32aligned_be64(&ps10->tx_dropped));
5506     ops->stats.rx_errors = ntohll(get_32aligned_be64(&ps10->rx_errors));
5507     ops->stats.tx_errors = ntohll(get_32aligned_be64(&ps10->tx_errors));
5508     ops->stats.rx_frame_errors =
5509         ntohll(get_32aligned_be64(&ps10->rx_frame_err));
5510     ops->stats.rx_over_errors = ntohll(get_32aligned_be64(&ps10->rx_over_err));
5511     ops->stats.rx_crc_errors = ntohll(get_32aligned_be64(&ps10->rx_crc_err));
5512     ops->stats.collisions = ntohll(get_32aligned_be64(&ps10->collisions));
5513     ops->duration_sec = ops->duration_nsec = UINT32_MAX;
5514
5515     return 0;
5516 }
5517
5518 static enum ofperr
5519 ofputil_port_stats_from_ofp11(struct ofputil_port_stats *ops,
5520                               const struct ofp11_port_stats *ps11)
5521 {
5522     enum ofperr error;
5523
5524     memset(ops, 0, sizeof *ops);
5525     error = ofputil_port_from_ofp11(ps11->port_no, &ops->port_no);
5526     if (error) {
5527         return error;
5528     }
5529
5530     ops->stats.rx_packets = ntohll(ps11->rx_packets);
5531     ops->stats.tx_packets = ntohll(ps11->tx_packets);
5532     ops->stats.rx_bytes = ntohll(ps11->rx_bytes);
5533     ops->stats.tx_bytes = ntohll(ps11->tx_bytes);
5534     ops->stats.rx_dropped = ntohll(ps11->rx_dropped);
5535     ops->stats.tx_dropped = ntohll(ps11->tx_dropped);
5536     ops->stats.rx_errors = ntohll(ps11->rx_errors);
5537     ops->stats.tx_errors = ntohll(ps11->tx_errors);
5538     ops->stats.rx_frame_errors = ntohll(ps11->rx_frame_err);
5539     ops->stats.rx_over_errors = ntohll(ps11->rx_over_err);
5540     ops->stats.rx_crc_errors = ntohll(ps11->rx_crc_err);
5541     ops->stats.collisions = ntohll(ps11->collisions);
5542     ops->duration_sec = ops->duration_nsec = UINT32_MAX;
5543
5544     return 0;
5545 }
5546
5547 static enum ofperr
5548 ofputil_port_stats_from_ofp13(struct ofputil_port_stats *ops,
5549                               const struct ofp13_port_stats *ps13)
5550 {
5551     enum ofperr error = ofputil_port_stats_from_ofp11(ops, &ps13->ps);
5552     if (!error) {
5553         ops->duration_sec = ntohl(ps13->duration_sec);
5554         ops->duration_nsec = ntohl(ps13->duration_nsec);
5555     }
5556     return error;
5557 }
5558
5559 static size_t
5560 ofputil_get_port_stats_size(enum ofp_version ofp_version)
5561 {
5562     switch (ofp_version) {
5563     case OFP10_VERSION:
5564         return sizeof(struct ofp10_port_stats);
5565     case OFP11_VERSION:
5566     case OFP12_VERSION:
5567         return sizeof(struct ofp11_port_stats);
5568     case OFP13_VERSION:
5569         return sizeof(struct ofp13_port_stats);
5570     default:
5571         NOT_REACHED();
5572     }
5573 }
5574
5575 /* Returns the number of port stats elements in OFPTYPE_PORT_STATS_REPLY
5576  * message 'oh'. */
5577 size_t
5578 ofputil_count_port_stats(const struct ofp_header *oh)
5579 {
5580     struct ofpbuf b;
5581
5582     ofpbuf_use_const(&b, oh, ntohs(oh->length));
5583     ofpraw_pull_assert(&b);
5584
5585     return b.size / ofputil_get_port_stats_size(oh->version);
5586 }
5587
5588 /* Converts an OFPST_PORT_STATS reply in 'msg' into an abstract
5589  * ofputil_port_stats in 'ps'.
5590  *
5591  * Multiple OFPST_PORT_STATS replies can be packed into a single OpenFlow
5592  * message.  Calling this function multiple times for a single 'msg' iterates
5593  * through the replies.  The caller must initially leave 'msg''s layer pointers
5594  * null and not modify them between calls.
5595  *
5596  * Returns 0 if successful, EOF if no replies were left in this 'msg',
5597  * otherwise a positive errno value. */
5598 int
5599 ofputil_decode_port_stats(struct ofputil_port_stats *ps, struct ofpbuf *msg)
5600 {
5601     enum ofperr error;
5602     enum ofpraw raw;
5603
5604     error = (msg->l2
5605              ? ofpraw_decode(&raw, msg->l2)
5606              : ofpraw_pull(&raw, msg));
5607     if (error) {
5608         return error;
5609     }
5610
5611     if (!msg->size) {
5612         return EOF;
5613     } else if (raw == OFPRAW_OFPST13_PORT_REPLY) {
5614         const struct ofp13_port_stats *ps13;
5615
5616         ps13 = ofpbuf_try_pull(msg, sizeof *ps13);
5617         if (!ps13) {
5618             goto bad_len;
5619         }
5620         return ofputil_port_stats_from_ofp13(ps, ps13);
5621     } else if (raw == OFPRAW_OFPST11_PORT_REPLY) {
5622         const struct ofp11_port_stats *ps11;
5623
5624         ps11 = ofpbuf_try_pull(msg, sizeof *ps11);
5625         if (!ps11) {
5626             goto bad_len;
5627         }
5628         return ofputil_port_stats_from_ofp11(ps, ps11);
5629     } else if (raw == OFPRAW_OFPST10_PORT_REPLY) {
5630         const struct ofp10_port_stats *ps10;
5631
5632         ps10 = ofpbuf_try_pull(msg, sizeof *ps10);
5633         if (!ps10) {
5634             goto bad_len;
5635         }
5636         return ofputil_port_stats_from_ofp10(ps, ps10);
5637     } else {
5638         NOT_REACHED();
5639     }
5640
5641  bad_len:
5642     VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_PORT reply has %zu leftover "
5643                  "bytes at end", msg->size);
5644     return OFPERR_OFPBRC_BAD_LEN;
5645 }
5646
5647 /* Parse a port status request message into a 16 bit OpenFlow 1.0
5648  * port number and stores the latter in '*ofp10_port'.
5649  * Returns 0 if successful, otherwise an OFPERR_* number. */
5650 enum ofperr
5651 ofputil_decode_port_stats_request(const struct ofp_header *request,
5652                                   ofp_port_t *ofp10_port)
5653 {
5654     switch ((enum ofp_version)request->version) {
5655     case OFP13_VERSION:
5656     case OFP12_VERSION:
5657     case OFP11_VERSION: {
5658         const struct ofp11_port_stats_request *psr11 = ofpmsg_body(request);
5659         return ofputil_port_from_ofp11(psr11->port_no, ofp10_port);
5660     }
5661
5662     case OFP10_VERSION: {
5663         const struct ofp10_port_stats_request *psr10 = ofpmsg_body(request);
5664         *ofp10_port = u16_to_ofp(ntohs(psr10->port_no));
5665         return 0;
5666     }
5667
5668     default:
5669         NOT_REACHED();
5670     }
5671 }
5672
5673 /* Frees all of the "struct ofputil_bucket"s in the 'buckets' list. */
5674 void
5675 ofputil_bucket_list_destroy(struct list *buckets)
5676 {
5677     struct ofputil_bucket *bucket, *next_bucket;
5678
5679     LIST_FOR_EACH_SAFE (bucket, next_bucket, list_node, buckets) {
5680         list_remove(&bucket->list_node);
5681         free(bucket->ofpacts);
5682         free(bucket);
5683     }
5684 }
5685
5686 /* Returns an OpenFlow group stats request for OpenFlow version 'ofp_version',
5687  * that requests stats for group 'group_id'.  (Use OFPG_ALL to request stats
5688  * for all groups.)
5689  *
5690  * Group statistics include packet and byte counts for each group. */
5691 struct ofpbuf *
5692 ofputil_encode_group_stats_request(enum ofp_version ofp_version,
5693                                    uint32_t group_id)
5694 {
5695     struct ofpbuf *request;
5696
5697     switch (ofp_version) {
5698     case OFP10_VERSION:
5699         ovs_fatal(0, "dump-group-stats needs OpenFlow 1.1 or later "
5700                      "(\'-O OpenFlow11\')");
5701     case OFP11_VERSION:
5702     case OFP12_VERSION:
5703     case OFP13_VERSION: {
5704         struct ofp11_group_stats_request *req;
5705         request = ofpraw_alloc(OFPRAW_OFPST11_GROUP_REQUEST, ofp_version, 0);
5706         req = ofpbuf_put_zeros(request, sizeof *req);
5707         req->group_id = htonl(group_id);
5708         break;
5709     }
5710     default:
5711         NOT_REACHED();
5712     }
5713
5714     return request;
5715 }
5716
5717 /* Returns an OpenFlow group description request for OpenFlow version
5718  * 'ofp_version', that requests stats for group 'group_id'.  (Use OFPG_ALL to
5719  * request stats for all groups.)
5720  *
5721  * Group descriptions include the bucket and action configuration for each
5722  * group. */
5723 struct ofpbuf *
5724 ofputil_encode_group_desc_request(enum ofp_version ofp_version)
5725 {
5726     struct ofpbuf *request;
5727
5728     switch (ofp_version) {
5729     case OFP10_VERSION:
5730         ovs_fatal(0, "dump-groups needs OpenFlow 1.1 or later "
5731                      "(\'-O OpenFlow11\')");
5732     case OFP11_VERSION:
5733     case OFP12_VERSION:
5734     case OFP13_VERSION: {
5735         request = ofpraw_alloc(OFPRAW_OFPST11_GROUP_DESC_REQUEST, ofp_version, 0);
5736         break;
5737     }
5738     default:
5739         NOT_REACHED();
5740     }
5741
5742     return request;
5743 }
5744
5745 static void *
5746 ofputil_group_stats_to_ofp11(const struct ofputil_group_stats *ogs,
5747                              size_t base_len, struct list *replies)
5748 {
5749     struct ofp11_bucket_counter *bc11;
5750     struct ofp11_group_stats *gs11;
5751     size_t length;
5752     int i;
5753
5754     length = base_len + sizeof(struct ofp11_bucket_counter) * ogs->n_buckets;
5755
5756     gs11 = ofpmp_append(replies, length);
5757     memset(gs11, 0, base_len);
5758     gs11->length = htons(length);
5759     gs11->group_id = htonl(ogs->group_id);
5760     gs11->ref_count = htonl(ogs->ref_count);
5761     gs11->packet_count = htonll(ogs->packet_count);
5762     gs11->byte_count = htonll(ogs->byte_count);
5763
5764     bc11 = (void *) (((uint8_t *) gs11) + base_len);
5765     for (i = 0; i < ogs->n_buckets; i++) {
5766         const struct bucket_counter *obc = &ogs->bucket_stats[i];
5767
5768         bc11[i].packet_count = htonll(obc->packet_count);
5769         bc11[i].byte_count = htonll(obc->byte_count);
5770     }
5771
5772     return gs11;
5773 }
5774
5775 static void
5776 ofputil_append_of13_group_stats(const struct ofputil_group_stats *ogs,
5777                                 struct list *replies)
5778 {
5779     struct ofp13_group_stats *gs13;
5780
5781     gs13 = ofputil_group_stats_to_ofp11(ogs, sizeof *gs13, replies);
5782     gs13->duration_sec = htonl(ogs->duration_sec);
5783     gs13->duration_nsec = htonl(ogs->duration_nsec);
5784 }
5785
5786 /* Encodes 'ogs' properly for the format of the list of group statistics
5787  * replies already begun in 'replies' and appends it to the list.  'replies'
5788  * must have originally been initialized with ofpmp_init(). */
5789 void
5790 ofputil_append_group_stats(struct list *replies,
5791                            const struct ofputil_group_stats *ogs)
5792 {
5793     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
5794     struct ofp_header *oh = msg->data;
5795
5796     switch ((enum ofp_version)oh->version) {
5797     case OFP11_VERSION:
5798     case OFP12_VERSION:
5799         ofputil_group_stats_to_ofp11(ogs, sizeof(struct ofp11_group_stats),
5800                                      replies);
5801         break;
5802
5803     case OFP13_VERSION:
5804         ofputil_append_of13_group_stats(ogs, replies);
5805         break;
5806
5807     case OFP10_VERSION:
5808     default:
5809         NOT_REACHED();
5810     }
5811 }
5812
5813 /* Returns an OpenFlow group features request for OpenFlow version
5814  * 'ofp_version'. */
5815 struct ofpbuf *
5816 ofputil_encode_group_features_request(enum ofp_version ofp_version)
5817 {
5818     struct ofpbuf *request = NULL;
5819
5820     switch (ofp_version) {
5821     case OFP10_VERSION:
5822     case OFP11_VERSION:
5823         ovs_fatal(0, "dump-group-features needs OpenFlow 1.2 or later "
5824                      "(\'-O OpenFlow12\')");
5825     case OFP12_VERSION:
5826     case OFP13_VERSION: {
5827         request = ofpraw_alloc(OFPRAW_OFPST12_GROUP_FEATURES_REQUEST,
5828                                         ofp_version, 0);
5829         break;
5830     }
5831     default:
5832         NOT_REACHED();
5833     }
5834
5835     return request;
5836 }
5837
5838 /* Returns a OpenFlow message that encodes 'features' properly as a reply to
5839  * group features request 'request'. */
5840 struct ofpbuf *
5841 ofputil_encode_group_features_reply(
5842     const struct ofputil_group_features *features,
5843     const struct ofp_header *request)
5844 {
5845     struct ofp12_group_features_stats *ogf;
5846     struct ofpbuf *reply;
5847
5848     reply = ofpraw_alloc_xid(OFPRAW_OFPST12_GROUP_FEATURES_REPLY,
5849                              request->version, request->xid, 0);
5850     ogf = ofpbuf_put_zeros(reply, sizeof *ogf);
5851     ogf->types = htonl(features->types);
5852     ogf->capabilities = htonl(features->capabilities);
5853     ogf->max_groups[0] = htonl(features->max_groups[0]);
5854     ogf->max_groups[1] = htonl(features->max_groups[1]);
5855     ogf->max_groups[2] = htonl(features->max_groups[2]);
5856     ogf->max_groups[3] = htonl(features->max_groups[3]);
5857     ogf->actions[0] = htonl(features->actions[0]);
5858     ogf->actions[1] = htonl(features->actions[1]);
5859     ogf->actions[2] = htonl(features->actions[2]);
5860     ogf->actions[3] = htonl(features->actions[3]);
5861
5862     return reply;
5863 }
5864
5865 /* Decodes group features reply 'oh' into 'features'. */
5866 void
5867 ofputil_decode_group_features_reply(const struct ofp_header *oh,
5868                                     struct ofputil_group_features *features)
5869 {
5870     const struct ofp12_group_features_stats *ogf = ofpmsg_body(oh);
5871
5872     features->types = ntohl(ogf->types);
5873     features->capabilities = ntohl(ogf->capabilities);
5874     features->max_groups[0] = ntohl(ogf->max_groups[0]);
5875     features->max_groups[1] = ntohl(ogf->max_groups[1]);
5876     features->max_groups[2] = ntohl(ogf->max_groups[2]);
5877     features->max_groups[3] = ntohl(ogf->max_groups[3]);
5878     features->actions[0] = ntohl(ogf->actions[0]);
5879     features->actions[1] = ntohl(ogf->actions[1]);
5880     features->actions[2] = ntohl(ogf->actions[2]);
5881     features->actions[3] = ntohl(ogf->actions[3]);
5882 }
5883
5884 /* Parse a group status request message into a 32 bit OpenFlow 1.1
5885  * group ID and stores the latter in '*group_id'.
5886  * Returns 0 if successful, otherwise an OFPERR_* number. */
5887 enum ofperr
5888 ofputil_decode_group_stats_request(const struct ofp_header *request,
5889                                    uint32_t *group_id)
5890 {
5891     const struct ofp11_group_stats_request *gsr11 = ofpmsg_body(request);
5892     *group_id = ntohl(gsr11->group_id);
5893     return 0;
5894 }
5895
5896 /* Converts a group stats reply in 'msg' into an abstract ofputil_group_stats
5897  * in 'gs'.  Assigns freshly allocated memory to gs->bucket_stats for the
5898  * caller to eventually free.
5899  *
5900  * Multiple group stats replies can be packed into a single OpenFlow message.
5901  * Calling this function multiple times for a single 'msg' iterates through the
5902  * replies.  The caller must initially leave 'msg''s layer pointers null and
5903  * not modify them between calls.
5904  *
5905  * Returns 0 if successful, EOF if no replies were left in this 'msg',
5906  * otherwise a positive errno value. */
5907 int
5908 ofputil_decode_group_stats_reply(struct ofpbuf *msg,
5909                                  struct ofputil_group_stats *gs)
5910 {
5911     struct ofp11_bucket_counter *obc;
5912     struct ofp11_group_stats *ogs11;
5913     enum ofpraw raw;
5914     enum ofperr error;
5915     size_t base_len;
5916     size_t length;
5917     size_t i;
5918
5919     gs->bucket_stats = NULL;
5920     error = (msg->l2
5921              ? ofpraw_decode(&raw, msg->l2)
5922              : ofpraw_pull(&raw, msg));
5923     if (error) {
5924         return error;
5925     }
5926
5927     if (!msg->size) {
5928         return EOF;
5929     }
5930
5931     if (raw == OFPRAW_OFPST11_GROUP_REPLY) {
5932         base_len = sizeof *ogs11;
5933         ogs11 = ofpbuf_try_pull(msg, sizeof *ogs11);
5934         gs->duration_sec = gs->duration_nsec = UINT32_MAX;
5935     } else if (raw == OFPRAW_OFPST13_GROUP_REPLY) {
5936         struct ofp13_group_stats *ogs13;
5937
5938         base_len = sizeof *ogs13;
5939         ogs13 = ofpbuf_try_pull(msg, sizeof *ogs13);
5940         if (ogs13) {
5941             ogs11 = &ogs13->gs;
5942             gs->duration_sec = ntohl(ogs13->duration_sec);
5943             gs->duration_nsec = ntohl(ogs13->duration_nsec);
5944         } else {
5945             ogs11 = NULL;
5946         }
5947     } else {
5948         NOT_REACHED();
5949     }
5950
5951     if (!ogs11) {
5952         VLOG_WARN_RL(&bad_ofmsg_rl, "%s reply has %zu leftover bytes at end",
5953                      ofpraw_get_name(raw), msg->size);
5954         return OFPERR_OFPBRC_BAD_LEN;
5955     }
5956     length = ntohs(ogs11->length);
5957     if (length < sizeof base_len) {
5958         VLOG_WARN_RL(&bad_ofmsg_rl, "%s reply claims invalid length %zu",
5959                      ofpraw_get_name(raw), length);
5960         return OFPERR_OFPBRC_BAD_LEN;
5961     }
5962
5963     gs->group_id = ntohl(ogs11->group_id);
5964     gs->ref_count = ntohl(ogs11->ref_count);
5965     gs->packet_count = ntohll(ogs11->packet_count);
5966     gs->byte_count = ntohll(ogs11->byte_count);
5967
5968     gs->n_buckets = (length - base_len) / sizeof *obc;
5969     obc = ofpbuf_try_pull(msg, gs->n_buckets * sizeof *obc);
5970     if (!obc) {
5971         VLOG_WARN_RL(&bad_ofmsg_rl, "%s reply has %zu leftover bytes at end",
5972                      ofpraw_get_name(raw), msg->size);
5973         return OFPERR_OFPBRC_BAD_LEN;
5974     }
5975
5976     gs->bucket_stats = xmalloc(gs->n_buckets * sizeof *gs->bucket_stats);
5977     for (i = 0; i < gs->n_buckets; i++) {
5978         gs->bucket_stats[i].packet_count = ntohll(obc[i].packet_count);
5979         gs->bucket_stats[i].byte_count = ntohll(obc[i].byte_count);
5980     }
5981
5982     return 0;
5983 }
5984
5985 /* Appends a group stats reply that contains the data in 'gds' to those already
5986  * present in the list of ofpbufs in 'replies'.  'replies' should have been
5987  * initialized with ofpmp_init(). */
5988 void
5989 ofputil_append_group_desc_reply(const struct ofputil_group_desc *gds,
5990                                 struct list *buckets,
5991                                 struct list *replies)
5992 {
5993     struct ofpbuf *reply = ofpbuf_from_list(list_back(replies));
5994     struct ofp11_group_desc_stats *ogds;
5995     struct ofputil_bucket *bucket;
5996     size_t start_ogds;
5997     enum ofp_version version = ((struct ofp_header *)reply->data)->version;
5998
5999     start_ogds = reply->size;
6000     ofpbuf_put_zeros(reply, sizeof *ogds);
6001     LIST_FOR_EACH (bucket, list_node, buckets) {
6002         struct ofp11_bucket *ob;
6003         size_t start_ob;
6004
6005         start_ob = reply->size;
6006         ofpbuf_put_zeros(reply, sizeof *ob);
6007         ofpacts_put_openflow_actions(bucket->ofpacts, bucket->ofpacts_len,
6008                                      reply, version);
6009         ob = ofpbuf_at_assert(reply, start_ob, sizeof *ob);
6010         ob->len = htons(reply->size - start_ob);
6011         ob->weight = htons(bucket->weight);
6012         ob->watch_port = ofputil_port_to_ofp11(bucket->watch_port);
6013         ob->watch_group = htonl(bucket->watch_group);
6014     }
6015     ogds = ofpbuf_at_assert(reply, start_ogds, sizeof *ogds);
6016     ogds->length = htons(reply->size - start_ogds);
6017     ogds->type = gds->type;
6018     ogds->group_id = htonl(gds->group_id);
6019
6020     ofpmp_postappend(replies, start_ogds);
6021 }
6022
6023 static enum ofperr
6024 ofputil_pull_buckets(struct ofpbuf *msg, size_t buckets_length,
6025                      enum ofp_version version, struct list *buckets)
6026 {
6027     struct ofp11_bucket *ob;
6028
6029     list_init(buckets);
6030     while (buckets_length > 0) {
6031         struct ofputil_bucket *bucket;
6032         struct ofpbuf ofpacts;
6033         enum ofperr error;
6034         size_t ob_len;
6035
6036         ob = (buckets_length >= sizeof *ob
6037               ? ofpbuf_try_pull(msg, sizeof *ob)
6038               : NULL);
6039         if (!ob) {
6040             VLOG_WARN_RL(&bad_ofmsg_rl, "buckets end with %zu leftover bytes",
6041                          buckets_length);
6042         }
6043
6044         ob_len = ntohs(ob->len);
6045         if (ob_len < sizeof *ob) {
6046             VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message bucket length "
6047                          "%zu is not valid", ob_len);
6048             return OFPERR_OFPGMFC_BAD_BUCKET;
6049         } else if (ob_len > buckets_length) {
6050             VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message bucket length "
6051                          "%zu exceeds remaining buckets data size %zu",
6052                          ob_len, buckets_length);
6053             return OFPERR_OFPGMFC_BAD_BUCKET;
6054         }
6055         buckets_length -= ob_len;
6056
6057         ofpbuf_init(&ofpacts, 0);
6058         error = ofpacts_pull_openflow_actions(msg, ob_len - sizeof *ob,
6059                                               version, &ofpacts);
6060         if (error) {
6061             ofpbuf_uninit(&ofpacts);
6062             ofputil_bucket_list_destroy(buckets);
6063             return error;
6064         }
6065
6066         bucket = xzalloc(sizeof *bucket);
6067         bucket->weight = ntohs(ob->weight);
6068         error = ofputil_port_from_ofp11(ob->watch_port, &bucket->watch_port);
6069         if (error) {
6070             ofpbuf_uninit(&ofpacts);
6071             ofputil_bucket_list_destroy(buckets);
6072             return OFPERR_OFPGMFC_BAD_WATCH;
6073         }
6074         bucket->watch_group = ntohl(ob->watch_group);
6075         bucket->ofpacts = ofpbuf_steal_data(&ofpacts);
6076         bucket->ofpacts_len = ofpacts.size;
6077         list_push_back(buckets, &bucket->list_node);
6078     }
6079
6080     return 0;
6081 }
6082
6083 /* Converts a group description reply in 'msg' into an abstract
6084  * ofputil_group_desc in 'gd'.
6085  *
6086  * Multiple group description replies can be packed into a single OpenFlow
6087  * message.  Calling this function multiple times for a single 'msg' iterates
6088  * through the replies.  The caller must initially leave 'msg''s layer pointers
6089  * null and not modify them between calls.
6090  *
6091  * Returns 0 if successful, EOF if no replies were left in this 'msg',
6092  * otherwise a positive errno value. */
6093 int
6094 ofputil_decode_group_desc_reply(struct ofputil_group_desc *gd,
6095                                 struct ofpbuf *msg, enum ofp_version version)
6096 {
6097     struct ofp11_group_desc_stats *ogds;
6098     size_t length;
6099
6100     if (!msg->l2) {
6101         ofpraw_pull_assert(msg);
6102     }
6103
6104     if (!msg->size) {
6105         return EOF;
6106     }
6107
6108     ogds = ofpbuf_try_pull(msg, sizeof *ogds);
6109     if (!ogds) {
6110         VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST11_GROUP_DESC reply has %zu "
6111                      "leftover bytes at end", msg->size);
6112         return OFPERR_OFPBRC_BAD_LEN;
6113     }
6114     gd->type = ogds->type;
6115     gd->group_id = ntohl(ogds->group_id);
6116
6117     length = ntohs(ogds->length);
6118     if (length < sizeof *ogds || length - sizeof *ogds > msg->size) {
6119         VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST11_GROUP_DESC reply claims invalid "
6120                      "length %zu", length);
6121         return OFPERR_OFPBRC_BAD_LEN;
6122     }
6123
6124     return ofputil_pull_buckets(msg, length - sizeof *ogds, version,
6125                                 &gd->buckets);
6126 }
6127
6128 /* Converts abstract group mod 'gm' into a message for OpenFlow version
6129  * 'ofp_version' and returns the message. */
6130 struct ofpbuf *
6131 ofputil_encode_group_mod(enum ofp_version ofp_version,
6132                          const struct ofputil_group_mod *gm)
6133 {
6134     struct ofpbuf *b;
6135     struct ofp11_group_mod *ogm;
6136     size_t start_ogm;
6137     size_t start_bucket;
6138     struct ofputil_bucket *bucket;
6139     struct ofp11_bucket *ob;
6140
6141     switch (ofp_version) {
6142     case OFP10_VERSION: {
6143         if (gm->command == OFPGC11_ADD) {
6144             ovs_fatal(0, "add-group needs OpenFlow 1.1 or later "
6145                          "(\'-O OpenFlow11\')");
6146         } else if (gm->command == OFPGC11_MODIFY) {
6147             ovs_fatal(0, "mod-group needs OpenFlow 1.1 or later "
6148                          "(\'-O OpenFlow11\')");
6149         } else {
6150             ovs_fatal(0, "del-groups needs OpenFlow 1.1 or later "
6151                          "(\'-O OpenFlow11\')");
6152         }
6153     }
6154
6155     case OFP11_VERSION:
6156     case OFP12_VERSION:
6157     case OFP13_VERSION: {
6158         b = ofpraw_alloc(OFPRAW_OFPT11_GROUP_MOD, ofp_version, 0);
6159         start_ogm = b->size;
6160         ofpbuf_put_uninit(b, sizeof *ogm);
6161
6162         LIST_FOR_EACH (bucket, list_node, &gm->buckets) {
6163             start_bucket = b->size;
6164             ofpbuf_put_uninit(b, sizeof *ob);
6165             if (bucket->ofpacts && bucket->ofpacts_len) {
6166                 ofpacts_put_openflow_actions(bucket->ofpacts,
6167                                              bucket->ofpacts_len, b,
6168                                              ofp_version);
6169             }
6170             ob = ofpbuf_at_assert(b, start_bucket, sizeof *ob);
6171             ob->len = htons(b->size - start_bucket);;
6172             ob->weight = htons(bucket->weight);
6173             ob->watch_port = ofputil_port_to_ofp11(bucket->watch_port);
6174             ob->watch_group = htonl(bucket->watch_group);
6175         }
6176         ogm = ofpbuf_at_assert(b, start_ogm, sizeof *ogm);
6177         ogm->command = htons(gm->command);
6178         ogm->type = gm->type;
6179         ogm->pad = 0;
6180         ogm->group_id = htonl(gm->group_id);
6181
6182         break;
6183     }
6184
6185     default:
6186         NOT_REACHED();
6187     }
6188
6189     return b;
6190 }
6191
6192 /* Converts OpenFlow group mod message 'oh' into an abstract group mod in
6193  * 'gm'.  Returns 0 if successful, otherwise an OpenFlow error code. */
6194 enum ofperr
6195 ofputil_decode_group_mod(const struct ofp_header *oh,
6196                          struct ofputil_group_mod *gm)
6197 {
6198     const struct ofp11_group_mod *ogm;
6199     struct ofpbuf msg;
6200
6201     ofpbuf_use_const(&msg, oh, ntohs(oh->length));
6202     ofpraw_pull_assert(&msg);
6203
6204     ogm = ofpbuf_pull(&msg, sizeof *ogm);
6205     gm->command = ntohs(ogm->command);
6206     gm->type = ogm->type;
6207     gm->group_id = ntohl(ogm->group_id);
6208
6209     return ofputil_pull_buckets(&msg, msg.size, oh->version, &gm->buckets);
6210 }
6211
6212 /* Parse a queue status request message into 'oqsr'.
6213  * Returns 0 if successful, otherwise an OFPERR_* number. */
6214 enum ofperr
6215 ofputil_decode_queue_stats_request(const struct ofp_header *request,
6216                                    struct ofputil_queue_stats_request *oqsr)
6217 {
6218     switch ((enum ofp_version)request->version) {
6219     case OFP13_VERSION:
6220     case OFP12_VERSION:
6221     case OFP11_VERSION: {
6222         const struct ofp11_queue_stats_request *qsr11 = ofpmsg_body(request);
6223         oqsr->queue_id = ntohl(qsr11->queue_id);
6224         return ofputil_port_from_ofp11(qsr11->port_no, &oqsr->port_no);
6225     }
6226
6227     case OFP10_VERSION: {
6228         const struct ofp10_queue_stats_request *qsr10 = ofpmsg_body(request);
6229         oqsr->queue_id = ntohl(qsr10->queue_id);
6230         oqsr->port_no = u16_to_ofp(ntohs(qsr10->port_no));
6231         /* OF 1.0 uses OFPP_ALL for OFPP_ANY */
6232         if (oqsr->port_no == OFPP_ALL) {
6233             oqsr->port_no = OFPP_ANY;
6234         }
6235         return 0;
6236     }
6237
6238     default:
6239         NOT_REACHED();
6240     }
6241 }
6242
6243 /* Encode a queue statsrequest for 'oqsr', the encoded message
6244  * will be fore Open Flow version 'ofp_version'. Returns message
6245  * as a struct ofpbuf. Returns encoded message on success, NULL on error */
6246 struct ofpbuf *
6247 ofputil_encode_queue_stats_request(enum ofp_version ofp_version,
6248                                    const struct ofputil_queue_stats_request *oqsr)
6249 {
6250     struct ofpbuf *request;
6251
6252     switch (ofp_version) {
6253     case OFP11_VERSION:
6254     case OFP12_VERSION:
6255     case OFP13_VERSION: {
6256         struct ofp11_queue_stats_request *req;
6257         request = ofpraw_alloc(OFPRAW_OFPST11_QUEUE_REQUEST, ofp_version, 0);
6258         req = ofpbuf_put_zeros(request, sizeof *req);
6259         req->port_no = ofputil_port_to_ofp11(oqsr->port_no);
6260         req->queue_id = htonl(oqsr->queue_id);
6261         break;
6262     }
6263     case OFP10_VERSION: {
6264         struct ofp10_queue_stats_request *req;
6265         request = ofpraw_alloc(OFPRAW_OFPST10_QUEUE_REQUEST, ofp_version, 0);
6266         req = ofpbuf_put_zeros(request, sizeof *req);
6267         /* OpenFlow 1.0 needs OFPP_ALL instead of OFPP_ANY */
6268         req->port_no = htons(ofp_to_u16(oqsr->port_no == OFPP_ANY
6269                                         ? OFPP_ALL : oqsr->port_no));
6270         req->queue_id = htonl(oqsr->queue_id);
6271         break;
6272     }
6273     default:
6274         NOT_REACHED();
6275     }
6276
6277     return request;
6278 }
6279
6280 static size_t
6281 ofputil_get_queue_stats_size(enum ofp_version ofp_version)
6282 {
6283     switch (ofp_version) {
6284     case OFP10_VERSION:
6285         return sizeof(struct ofp10_queue_stats);
6286     case OFP11_VERSION:
6287     case OFP12_VERSION:
6288         return sizeof(struct ofp11_queue_stats);
6289     case OFP13_VERSION:
6290         return sizeof(struct ofp13_queue_stats);
6291     default:
6292         NOT_REACHED();
6293     }
6294 }
6295
6296 /* Returns the number of queue stats elements in OFPTYPE_QUEUE_STATS_REPLY
6297  * message 'oh'. */
6298 size_t
6299 ofputil_count_queue_stats(const struct ofp_header *oh)
6300 {
6301     struct ofpbuf b;
6302
6303     ofpbuf_use_const(&b, oh, ntohs(oh->length));
6304     ofpraw_pull_assert(&b);
6305
6306     return b.size / ofputil_get_queue_stats_size(oh->version);
6307 }
6308
6309 static enum ofperr
6310 ofputil_queue_stats_from_ofp10(struct ofputil_queue_stats *oqs,
6311                                const struct ofp10_queue_stats *qs10)
6312 {
6313     oqs->port_no = u16_to_ofp(ntohs(qs10->port_no));
6314     oqs->queue_id = ntohl(qs10->queue_id);
6315     oqs->tx_bytes = ntohll(get_32aligned_be64(&qs10->tx_bytes));
6316     oqs->tx_packets = ntohll(get_32aligned_be64(&qs10->tx_packets));
6317     oqs->tx_errors = ntohll(get_32aligned_be64(&qs10->tx_errors));
6318     oqs->duration_sec = oqs->duration_nsec = UINT32_MAX;
6319
6320     return 0;
6321 }
6322
6323 static enum ofperr
6324 ofputil_queue_stats_from_ofp11(struct ofputil_queue_stats *oqs,
6325                                const struct ofp11_queue_stats *qs11)
6326 {
6327     enum ofperr error;
6328
6329     error = ofputil_port_from_ofp11(qs11->port_no, &oqs->port_no);
6330     if (error) {
6331         return error;
6332     }
6333
6334     oqs->queue_id = ntohl(qs11->queue_id);
6335     oqs->tx_bytes = ntohll(qs11->tx_bytes);
6336     oqs->tx_packets = ntohll(qs11->tx_packets);
6337     oqs->tx_errors = ntohll(qs11->tx_errors);
6338     oqs->duration_sec = oqs->duration_nsec = UINT32_MAX;
6339
6340     return 0;
6341 }
6342
6343 static enum ofperr
6344 ofputil_queue_stats_from_ofp13(struct ofputil_queue_stats *oqs,
6345                                const struct ofp13_queue_stats *qs13)
6346 {
6347     enum ofperr error = ofputil_queue_stats_from_ofp11(oqs, &qs13->qs);
6348     if (!error) {
6349         oqs->duration_sec = ntohl(qs13->duration_sec);
6350         oqs->duration_nsec = ntohl(qs13->duration_nsec);
6351     }
6352
6353     return error;
6354 }
6355
6356 /* Converts an OFPST_QUEUE_STATS reply in 'msg' into an abstract
6357  * ofputil_queue_stats in 'qs'.
6358  *
6359  * Multiple OFPST_QUEUE_STATS replies can be packed into a single OpenFlow
6360  * message.  Calling this function multiple times for a single 'msg' iterates
6361  * through the replies.  The caller must initially leave 'msg''s layer pointers
6362  * null and not modify them between calls.
6363  *
6364  * Returns 0 if successful, EOF if no replies were left in this 'msg',
6365  * otherwise a positive errno value. */
6366 int
6367 ofputil_decode_queue_stats(struct ofputil_queue_stats *qs, struct ofpbuf *msg)
6368 {
6369     enum ofperr error;
6370     enum ofpraw raw;
6371
6372     error = (msg->l2
6373              ? ofpraw_decode(&raw, msg->l2)
6374              : ofpraw_pull(&raw, msg));
6375     if (error) {
6376         return error;
6377     }
6378
6379     if (!msg->size) {
6380         return EOF;
6381     } else if (raw == OFPRAW_OFPST13_QUEUE_REPLY) {
6382         const struct ofp13_queue_stats *qs13;
6383
6384         qs13 = ofpbuf_try_pull(msg, sizeof *qs13);
6385         if (!qs13) {
6386             goto bad_len;
6387         }
6388         return ofputil_queue_stats_from_ofp13(qs, qs13);
6389     } else if (raw == OFPRAW_OFPST11_QUEUE_REPLY) {
6390         const struct ofp11_queue_stats *qs11;
6391
6392         qs11 = ofpbuf_try_pull(msg, sizeof *qs11);
6393         if (!qs11) {
6394             goto bad_len;
6395         }
6396         return ofputil_queue_stats_from_ofp11(qs, qs11);
6397     } else if (raw == OFPRAW_OFPST10_QUEUE_REPLY) {
6398         const struct ofp10_queue_stats *qs10;
6399
6400         qs10 = ofpbuf_try_pull(msg, sizeof *qs10);
6401         if (!qs10) {
6402             goto bad_len;
6403         }
6404         return ofputil_queue_stats_from_ofp10(qs, qs10);
6405     } else {
6406         NOT_REACHED();
6407     }
6408
6409  bad_len:
6410     VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_QUEUE reply has %zu leftover "
6411                  "bytes at end", msg->size);
6412     return OFPERR_OFPBRC_BAD_LEN;
6413 }
6414
6415 static void
6416 ofputil_queue_stats_to_ofp10(const struct ofputil_queue_stats *oqs,
6417                              struct ofp10_queue_stats *qs10)
6418 {
6419     qs10->port_no = htons(ofp_to_u16(oqs->port_no));
6420     memset(qs10->pad, 0, sizeof qs10->pad);
6421     qs10->queue_id = htonl(oqs->queue_id);
6422     put_32aligned_be64(&qs10->tx_bytes, htonll(oqs->tx_bytes));
6423     put_32aligned_be64(&qs10->tx_packets, htonll(oqs->tx_packets));
6424     put_32aligned_be64(&qs10->tx_errors, htonll(oqs->tx_errors));
6425 }
6426
6427 static void
6428 ofputil_queue_stats_to_ofp11(const struct ofputil_queue_stats *oqs,
6429                              struct ofp11_queue_stats *qs11)
6430 {
6431     qs11->port_no = ofputil_port_to_ofp11(oqs->port_no);
6432     qs11->queue_id = htonl(oqs->queue_id);
6433     qs11->tx_bytes = htonll(oqs->tx_bytes);
6434     qs11->tx_packets = htonll(oqs->tx_packets);
6435     qs11->tx_errors = htonll(oqs->tx_errors);
6436 }
6437
6438 static void
6439 ofputil_queue_stats_to_ofp13(const struct ofputil_queue_stats *oqs,
6440                              struct ofp13_queue_stats *qs13)
6441 {
6442     ofputil_queue_stats_to_ofp11(oqs, &qs13->qs);
6443     if (oqs->duration_sec != UINT32_MAX) {
6444         qs13->duration_sec = htonl(oqs->duration_sec);
6445         qs13->duration_nsec = htonl(oqs->duration_nsec);
6446     } else {
6447         qs13->duration_sec = OVS_BE32_MAX;
6448         qs13->duration_nsec = OVS_BE32_MAX;
6449     }
6450 }
6451
6452 /* Encode a queue stat for 'oqs' and append it to 'replies'. */
6453 void
6454 ofputil_append_queue_stat(struct list *replies,
6455                           const struct ofputil_queue_stats *oqs)
6456 {
6457     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
6458     struct ofp_header *oh = msg->data;
6459
6460     switch ((enum ofp_version)oh->version) {
6461     case OFP13_VERSION: {
6462         struct ofp13_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
6463         ofputil_queue_stats_to_ofp13(oqs, reply);
6464         break;
6465     }
6466
6467     case OFP12_VERSION:
6468     case OFP11_VERSION: {
6469         struct ofp11_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
6470         ofputil_queue_stats_to_ofp11(oqs, reply);
6471         break;
6472     }
6473
6474     case OFP10_VERSION: {
6475         struct ofp10_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
6476         ofputil_queue_stats_to_ofp10(oqs, reply);
6477         break;
6478     }
6479
6480     default:
6481         NOT_REACHED();
6482     }
6483 }