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