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