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