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