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