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