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