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