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