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