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