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