ofp-util: Fix port desc request encoding.
[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 == 33);
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
3998     switch (ofp_version) {
3999     case OFP10_VERSION:
4000     case OFP11_VERSION:
4001     case OFP12_VERSION:
4002     case OFP13_VERSION:
4003     case OFP14_VERSION:
4004         request = ofpraw_alloc(OFPRAW_OFPST10_PORT_DESC_REQUEST,
4005                                ofp_version, 0);
4006         break;
4007     case OFP15_VERSION:{
4008         struct ofp15_port_desc_request *req;
4009         request = ofpraw_alloc(OFPRAW_OFPST15_PORT_DESC_REQUEST,
4010                                ofp_version, 0);
4011         req = ofpbuf_put_zeros(request, sizeof *req);
4012         req->port_no = ofputil_port_to_ofp11(port);
4013         break;
4014     }
4015     default:
4016         OVS_NOT_REACHED();
4017     }
4018
4019     return request;
4020 }
4021
4022 void
4023 ofputil_append_port_desc_stats_reply(const struct ofputil_phy_port *pp,
4024                                      struct ovs_list *replies)
4025 {
4026     struct ofpbuf *reply = ofpbuf_from_list(list_back(replies));
4027     size_t start_ofs = reply->size;
4028
4029     ofputil_put_phy_port(ofpmp_version(replies), pp, reply);
4030     ofpmp_postappend(replies, start_ofs);
4031 }
4032 \f
4033 /* ofputil_switch_features */
4034
4035 #define OFPC_COMMON (OFPC_FLOW_STATS | OFPC_TABLE_STATS | OFPC_PORT_STATS | \
4036                      OFPC_IP_REASM | OFPC_QUEUE_STATS)
4037 BUILD_ASSERT_DECL((int) OFPUTIL_C_FLOW_STATS == OFPC_FLOW_STATS);
4038 BUILD_ASSERT_DECL((int) OFPUTIL_C_TABLE_STATS == OFPC_TABLE_STATS);
4039 BUILD_ASSERT_DECL((int) OFPUTIL_C_PORT_STATS == OFPC_PORT_STATS);
4040 BUILD_ASSERT_DECL((int) OFPUTIL_C_IP_REASM == OFPC_IP_REASM);
4041 BUILD_ASSERT_DECL((int) OFPUTIL_C_QUEUE_STATS == OFPC_QUEUE_STATS);
4042 BUILD_ASSERT_DECL((int) OFPUTIL_C_ARP_MATCH_IP == OFPC_ARP_MATCH_IP);
4043
4044 static uint32_t
4045 ofputil_capabilities_mask(enum ofp_version ofp_version)
4046 {
4047     /* Handle capabilities whose bit is unique for all OpenFlow versions */
4048     switch (ofp_version) {
4049     case OFP10_VERSION:
4050     case OFP11_VERSION:
4051         return OFPC_COMMON | OFPC_ARP_MATCH_IP;
4052     case OFP12_VERSION:
4053     case OFP13_VERSION:
4054     case OFP14_VERSION:
4055     case OFP15_VERSION:
4056         return OFPC_COMMON | OFPC12_PORT_BLOCKED;
4057     default:
4058         /* Caller needs to check osf->header.version itself */
4059         return 0;
4060     }
4061 }
4062
4063 /* Decodes an OpenFlow 1.0 or 1.1 "switch_features" structure 'osf' into an
4064  * abstract representation in '*features'.  Initializes '*b' to iterate over
4065  * the OpenFlow port structures following 'osf' with later calls to
4066  * ofputil_pull_phy_port().  Returns 0 if successful, otherwise an
4067  * OFPERR_* value.  */
4068 enum ofperr
4069 ofputil_decode_switch_features(const struct ofp_header *oh,
4070                                struct ofputil_switch_features *features,
4071                                struct ofpbuf *b)
4072 {
4073     const struct ofp_switch_features *osf;
4074     enum ofpraw raw;
4075
4076     ofpbuf_use_const(b, oh, ntohs(oh->length));
4077     raw = ofpraw_pull_assert(b);
4078
4079     osf = ofpbuf_pull(b, sizeof *osf);
4080     features->datapath_id = ntohll(osf->datapath_id);
4081     features->n_buffers = ntohl(osf->n_buffers);
4082     features->n_tables = osf->n_tables;
4083     features->auxiliary_id = 0;
4084
4085     features->capabilities = ntohl(osf->capabilities) &
4086         ofputil_capabilities_mask(oh->version);
4087
4088     if (raw == OFPRAW_OFPT10_FEATURES_REPLY) {
4089         if (osf->capabilities & htonl(OFPC10_STP)) {
4090             features->capabilities |= OFPUTIL_C_STP;
4091         }
4092         features->ofpacts = ofpact_bitmap_from_openflow(osf->actions,
4093                                                         OFP10_VERSION);
4094     } else if (raw == OFPRAW_OFPT11_FEATURES_REPLY
4095                || raw == OFPRAW_OFPT13_FEATURES_REPLY) {
4096         if (osf->capabilities & htonl(OFPC11_GROUP_STATS)) {
4097             features->capabilities |= OFPUTIL_C_GROUP_STATS;
4098         }
4099         features->ofpacts = 0;
4100         if (raw == OFPRAW_OFPT13_FEATURES_REPLY) {
4101             features->auxiliary_id = osf->auxiliary_id;
4102         }
4103     } else {
4104         return OFPERR_OFPBRC_BAD_VERSION;
4105     }
4106
4107     return 0;
4108 }
4109
4110 /* In OpenFlow 1.0, 1.1, and 1.2, an OFPT_FEATURES_REPLY message lists all the
4111  * switch's ports, unless there are too many to fit.  In OpenFlow 1.3 and
4112  * later, an OFPT_FEATURES_REPLY does not list ports at all.
4113  *
4114  * Given a buffer 'b' that contains a Features Reply message, this message
4115  * checks if it contains a complete list of the switch's ports.  Returns true,
4116  * if so.  Returns false if the list is missing (OF1.3+) or incomplete
4117  * (OF1.0/1.1/1.2), and in the latter case removes all of the ports from the
4118  * message.
4119  *
4120  * When this function returns false, the caller should send an OFPST_PORT_DESC
4121  * stats request to get the ports. */
4122 bool
4123 ofputil_switch_features_has_ports(struct ofpbuf *b)
4124 {
4125     struct ofp_header *oh = b->data;
4126     size_t phy_port_size;
4127
4128     if (oh->version >= OFP13_VERSION) {
4129         /* OpenFlow 1.3+ never has ports in the feature reply. */
4130         return false;
4131     }
4132
4133     phy_port_size = (oh->version == OFP10_VERSION
4134                      ? sizeof(struct ofp10_phy_port)
4135                      : sizeof(struct ofp11_port));
4136     if (ntohs(oh->length) + phy_port_size <= UINT16_MAX) {
4137         /* There's room for additional ports in the feature reply.
4138          * Assume that the list is complete. */
4139         return true;
4140     }
4141
4142     /* The feature reply has no room for more ports.  Probably the list is
4143      * truncated.  Drop the ports and tell the caller to retrieve them with
4144      * OFPST_PORT_DESC. */
4145     b->size = sizeof *oh + sizeof(struct ofp_switch_features);
4146     ofpmsg_update_length(b);
4147     return false;
4148 }
4149
4150 /* Returns a buffer owned by the caller that encodes 'features' in the format
4151  * required by 'protocol' with the given 'xid'.  The caller should append port
4152  * information to the buffer with subsequent calls to
4153  * ofputil_put_switch_features_port(). */
4154 struct ofpbuf *
4155 ofputil_encode_switch_features(const struct ofputil_switch_features *features,
4156                                enum ofputil_protocol protocol, ovs_be32 xid)
4157 {
4158     struct ofp_switch_features *osf;
4159     struct ofpbuf *b;
4160     enum ofp_version version;
4161     enum ofpraw raw;
4162
4163     version = ofputil_protocol_to_ofp_version(protocol);
4164     switch (version) {
4165     case OFP10_VERSION:
4166         raw = OFPRAW_OFPT10_FEATURES_REPLY;
4167         break;
4168     case OFP11_VERSION:
4169     case OFP12_VERSION:
4170         raw = OFPRAW_OFPT11_FEATURES_REPLY;
4171         break;
4172     case OFP13_VERSION:
4173     case OFP14_VERSION:
4174     case OFP15_VERSION:
4175         raw = OFPRAW_OFPT13_FEATURES_REPLY;
4176         break;
4177     default:
4178         OVS_NOT_REACHED();
4179     }
4180     b = ofpraw_alloc_xid(raw, version, xid, 0);
4181     osf = ofpbuf_put_zeros(b, sizeof *osf);
4182     osf->datapath_id = htonll(features->datapath_id);
4183     osf->n_buffers = htonl(features->n_buffers);
4184     osf->n_tables = features->n_tables;
4185
4186     osf->capabilities = htonl(features->capabilities & OFPC_COMMON);
4187     osf->capabilities = htonl(features->capabilities &
4188                               ofputil_capabilities_mask(version));
4189     switch (version) {
4190     case OFP10_VERSION:
4191         if (features->capabilities & OFPUTIL_C_STP) {
4192             osf->capabilities |= htonl(OFPC10_STP);
4193         }
4194         osf->actions = ofpact_bitmap_to_openflow(features->ofpacts,
4195                                                  OFP10_VERSION);
4196         break;
4197     case OFP13_VERSION:
4198     case OFP14_VERSION:
4199     case OFP15_VERSION:
4200         osf->auxiliary_id = features->auxiliary_id;
4201         /* fall through */
4202     case OFP11_VERSION:
4203     case OFP12_VERSION:
4204         if (features->capabilities & OFPUTIL_C_GROUP_STATS) {
4205             osf->capabilities |= htonl(OFPC11_GROUP_STATS);
4206         }
4207         break;
4208     default:
4209         OVS_NOT_REACHED();
4210     }
4211
4212     return b;
4213 }
4214
4215 /* Encodes 'pp' into the format required by the switch_features message already
4216  * in 'b', which should have been returned by ofputil_encode_switch_features(),
4217  * and appends the encoded version to 'b'. */
4218 void
4219 ofputil_put_switch_features_port(const struct ofputil_phy_port *pp,
4220                                  struct ofpbuf *b)
4221 {
4222     const struct ofp_header *oh = b->data;
4223
4224     if (oh->version < OFP13_VERSION) {
4225         /* Try adding a port description to the message, but drop it again if
4226          * the buffer overflows.  (This possibility for overflow is why
4227          * OpenFlow 1.3+ moved port descriptions into a multipart message.)  */
4228         size_t start_ofs = b->size;
4229         ofputil_put_phy_port(oh->version, pp, b);
4230         if (b->size > UINT16_MAX) {
4231             b->size = start_ofs;
4232         }
4233     }
4234 }
4235 \f
4236 /* ofputil_port_status */
4237
4238 /* Decodes the OpenFlow "port status" message in '*ops' into an abstract form
4239  * in '*ps'.  Returns 0 if successful, otherwise an OFPERR_* value. */
4240 enum ofperr
4241 ofputil_decode_port_status(const struct ofp_header *oh,
4242                            struct ofputil_port_status *ps)
4243 {
4244     const struct ofp_port_status *ops;
4245     struct ofpbuf b;
4246     int retval;
4247
4248     ofpbuf_use_const(&b, oh, ntohs(oh->length));
4249     ofpraw_pull_assert(&b);
4250     ops = ofpbuf_pull(&b, sizeof *ops);
4251
4252     if (ops->reason != OFPPR_ADD &&
4253         ops->reason != OFPPR_DELETE &&
4254         ops->reason != OFPPR_MODIFY) {
4255         return OFPERR_NXBRC_BAD_REASON;
4256     }
4257     ps->reason = ops->reason;
4258
4259     retval = ofputil_pull_phy_port(oh->version, &b, &ps->desc);
4260     ovs_assert(retval != EOF);
4261     return retval;
4262 }
4263
4264 /* Converts the abstract form of a "port status" message in '*ps' into an
4265  * OpenFlow message suitable for 'protocol', and returns that encoded form in
4266  * a buffer owned by the caller. */
4267 struct ofpbuf *
4268 ofputil_encode_port_status(const struct ofputil_port_status *ps,
4269                            enum ofputil_protocol protocol)
4270 {
4271     struct ofp_port_status *ops;
4272     struct ofpbuf *b;
4273     enum ofp_version version;
4274     enum ofpraw raw;
4275
4276     version = ofputil_protocol_to_ofp_version(protocol);
4277     switch (version) {
4278     case OFP10_VERSION:
4279         raw = OFPRAW_OFPT10_PORT_STATUS;
4280         break;
4281
4282     case OFP11_VERSION:
4283     case OFP12_VERSION:
4284     case OFP13_VERSION:
4285         raw = OFPRAW_OFPT11_PORT_STATUS;
4286         break;
4287
4288     case OFP14_VERSION:
4289     case OFP15_VERSION:
4290         raw = OFPRAW_OFPT14_PORT_STATUS;
4291         break;
4292
4293     default:
4294         OVS_NOT_REACHED();
4295     }
4296
4297     b = ofpraw_alloc_xid(raw, version, htonl(0), 0);
4298     ops = ofpbuf_put_zeros(b, sizeof *ops);
4299     ops->reason = ps->reason;
4300     ofputil_put_phy_port(version, &ps->desc, b);
4301     ofpmsg_update_length(b);
4302     return b;
4303 }
4304
4305 /* ofputil_port_mod */
4306
4307 static enum ofperr
4308 parse_port_mod_ethernet_property(struct ofpbuf *property,
4309                                  struct ofputil_port_mod *pm)
4310 {
4311     struct ofp14_port_mod_prop_ethernet *eth = property->data;
4312
4313     if (property->size != sizeof *eth) {
4314         return OFPERR_OFPBRC_BAD_LEN;
4315     }
4316
4317     pm->advertise = netdev_port_features_from_ofp11(eth->advertise);
4318     return 0;
4319 }
4320
4321 /* Decodes the OpenFlow "port mod" message in '*oh' into an abstract form in
4322  * '*pm'.  Returns 0 if successful, otherwise an OFPERR_* value. */
4323 enum ofperr
4324 ofputil_decode_port_mod(const struct ofp_header *oh,
4325                         struct ofputil_port_mod *pm, bool loose)
4326 {
4327     enum ofpraw raw;
4328     struct ofpbuf b;
4329
4330     ofpbuf_use_const(&b, oh, ntohs(oh->length));
4331     raw = ofpraw_pull_assert(&b);
4332
4333     if (raw == OFPRAW_OFPT10_PORT_MOD) {
4334         const struct ofp10_port_mod *opm = b.data;
4335
4336         pm->port_no = u16_to_ofp(ntohs(opm->port_no));
4337         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
4338         pm->config = ntohl(opm->config) & OFPPC10_ALL;
4339         pm->mask = ntohl(opm->mask) & OFPPC10_ALL;
4340         pm->advertise = netdev_port_features_from_ofp10(opm->advertise);
4341     } else if (raw == OFPRAW_OFPT11_PORT_MOD) {
4342         const struct ofp11_port_mod *opm = b.data;
4343         enum ofperr error;
4344
4345         error = ofputil_port_from_ofp11(opm->port_no, &pm->port_no);
4346         if (error) {
4347             return error;
4348         }
4349
4350         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
4351         pm->config = ntohl(opm->config) & OFPPC11_ALL;
4352         pm->mask = ntohl(opm->mask) & OFPPC11_ALL;
4353         pm->advertise = netdev_port_features_from_ofp11(opm->advertise);
4354     } else if (raw == OFPRAW_OFPT14_PORT_MOD) {
4355         const struct ofp14_port_mod *opm = ofpbuf_pull(&b, sizeof *opm);
4356         enum ofperr error;
4357
4358         memset(pm, 0, sizeof *pm);
4359
4360         error = ofputil_port_from_ofp11(opm->port_no, &pm->port_no);
4361         if (error) {
4362             return error;
4363         }
4364
4365         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
4366         pm->config = ntohl(opm->config) & OFPPC11_ALL;
4367         pm->mask = ntohl(opm->mask) & OFPPC11_ALL;
4368
4369         while (b.size > 0) {
4370             struct ofpbuf property;
4371             enum ofperr error;
4372             uint16_t type;
4373
4374             error = ofputil_pull_property(&b, &property, &type);
4375             if (error) {
4376                 return error;
4377             }
4378
4379             switch (type) {
4380             case OFPPMPT14_ETHERNET:
4381                 error = parse_port_mod_ethernet_property(&property, pm);
4382                 break;
4383
4384             default:
4385                 log_property(loose, "unknown port_mod property %"PRIu16, type);
4386                 if (loose) {
4387                     error = 0;
4388                 } else if (type == OFPPMPT14_EXPERIMENTER) {
4389                     error = OFPERR_OFPBPC_BAD_EXPERIMENTER;
4390                 } else {
4391                     error = OFPERR_OFPBRC_BAD_TYPE;
4392                 }
4393                 break;
4394             }
4395
4396             if (error) {
4397                 return error;
4398             }
4399         }
4400     } else {
4401         return OFPERR_OFPBRC_BAD_TYPE;
4402     }
4403
4404     pm->config &= pm->mask;
4405     return 0;
4406 }
4407
4408 /* Converts the abstract form of a "port mod" message in '*pm' into an OpenFlow
4409  * message suitable for 'protocol', and returns that encoded form in a buffer
4410  * owned by the caller. */
4411 struct ofpbuf *
4412 ofputil_encode_port_mod(const struct ofputil_port_mod *pm,
4413                         enum ofputil_protocol protocol)
4414 {
4415     enum ofp_version ofp_version = ofputil_protocol_to_ofp_version(protocol);
4416     struct ofpbuf *b;
4417
4418     switch (ofp_version) {
4419     case OFP10_VERSION: {
4420         struct ofp10_port_mod *opm;
4421
4422         b = ofpraw_alloc(OFPRAW_OFPT10_PORT_MOD, ofp_version, 0);
4423         opm = ofpbuf_put_zeros(b, sizeof *opm);
4424         opm->port_no = htons(ofp_to_u16(pm->port_no));
4425         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
4426         opm->config = htonl(pm->config & OFPPC10_ALL);
4427         opm->mask = htonl(pm->mask & OFPPC10_ALL);
4428         opm->advertise = netdev_port_features_to_ofp10(pm->advertise);
4429         break;
4430     }
4431
4432     case OFP11_VERSION:
4433     case OFP12_VERSION:
4434     case OFP13_VERSION: {
4435         struct ofp11_port_mod *opm;
4436
4437         b = ofpraw_alloc(OFPRAW_OFPT11_PORT_MOD, ofp_version, 0);
4438         opm = ofpbuf_put_zeros(b, sizeof *opm);
4439         opm->port_no = ofputil_port_to_ofp11(pm->port_no);
4440         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
4441         opm->config = htonl(pm->config & OFPPC11_ALL);
4442         opm->mask = htonl(pm->mask & OFPPC11_ALL);
4443         opm->advertise = netdev_port_features_to_ofp11(pm->advertise);
4444         break;
4445     }
4446     case OFP14_VERSION:
4447     case OFP15_VERSION: {
4448         struct ofp14_port_mod_prop_ethernet *eth;
4449         struct ofp14_port_mod *opm;
4450
4451         b = ofpraw_alloc(OFPRAW_OFPT14_PORT_MOD, ofp_version, sizeof *eth);
4452         opm = ofpbuf_put_zeros(b, sizeof *opm);
4453         opm->port_no = ofputil_port_to_ofp11(pm->port_no);
4454         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
4455         opm->config = htonl(pm->config & OFPPC11_ALL);
4456         opm->mask = htonl(pm->mask & OFPPC11_ALL);
4457
4458         if (pm->advertise) {
4459             eth = ofpbuf_put_zeros(b, sizeof *eth);
4460             eth->type = htons(OFPPMPT14_ETHERNET);
4461             eth->length = htons(sizeof *eth);
4462             eth->advertise = netdev_port_features_to_ofp11(pm->advertise);
4463         }
4464         break;
4465     }
4466     default:
4467         OVS_NOT_REACHED();
4468     }
4469
4470     return b;
4471 }
4472 \f
4473 /* Table features. */
4474
4475 static enum ofperr
4476 pull_table_feature_property(struct ofpbuf *msg, struct ofpbuf *payload,
4477                             uint16_t *typep)
4478 {
4479     enum ofperr error;
4480
4481     error = ofputil_pull_property(msg, payload, typep);
4482     if (payload && !error) {
4483         ofpbuf_pull(payload, sizeof(struct ofp_prop_header));
4484     }
4485     return error;
4486 }
4487
4488 static enum ofperr
4489 parse_action_bitmap(struct ofpbuf *payload, enum ofp_version ofp_version,
4490                     uint64_t *ofpacts)
4491 {
4492     uint32_t types = 0;
4493
4494     while (payload->size > 0) {
4495         uint16_t type;
4496         enum ofperr error;
4497
4498         error = ofputil_pull_property__(payload, NULL, 1, &type);
4499         if (error) {
4500             return error;
4501         }
4502         if (type < CHAR_BIT * sizeof types) {
4503             types |= 1u << type;
4504         }
4505     }
4506
4507     *ofpacts = ofpact_bitmap_from_openflow(htonl(types), ofp_version);
4508     return 0;
4509 }
4510
4511 static enum ofperr
4512 parse_instruction_ids(struct ofpbuf *payload, bool loose, uint32_t *insts)
4513 {
4514     *insts = 0;
4515     while (payload->size > 0) {
4516         enum ovs_instruction_type inst;
4517         enum ofperr error;
4518         uint16_t ofpit;
4519
4520         /* OF1.3 and OF1.4 aren't clear about padding in the instruction IDs.
4521          * It seems clear that they aren't padded to 8 bytes, though, because
4522          * both standards say that "non-experimenter instructions are 4 bytes"
4523          * and do not mention any padding before the first instruction ID.
4524          * (There wouldn't be any point in padding to 8 bytes if the IDs were
4525          * aligned on an odd 4-byte boundary.)
4526          *
4527          * Anyway, we just assume they're all glommed together on byte
4528          * boundaries. */
4529         error = ofputil_pull_property__(payload, NULL, 1, &ofpit);
4530         if (error) {
4531             return error;
4532         }
4533
4534         error = ovs_instruction_type_from_inst_type(&inst, ofpit);
4535         if (!error) {
4536             *insts |= 1u << inst;
4537         } else if (!loose) {
4538             return error;
4539         }
4540     }
4541     return 0;
4542 }
4543
4544 static enum ofperr
4545 parse_table_features_next_table(struct ofpbuf *payload,
4546                                 unsigned long int *next_tables)
4547 {
4548     size_t i;
4549
4550     memset(next_tables, 0, bitmap_n_bytes(255));
4551     for (i = 0; i < payload->size; i++) {
4552         uint8_t id = ((const uint8_t *) payload->data)[i];
4553         if (id >= 255) {
4554             return OFPERR_OFPBPC_BAD_VALUE;
4555         }
4556         bitmap_set1(next_tables, id);
4557     }
4558     return 0;
4559 }
4560
4561 static enum ofperr
4562 parse_oxms(struct ofpbuf *payload, bool loose,
4563            struct mf_bitmap *exactp, struct mf_bitmap *maskedp)
4564 {
4565     struct mf_bitmap exact = MF_BITMAP_INITIALIZER;
4566     struct mf_bitmap masked = MF_BITMAP_INITIALIZER;
4567
4568     while (payload->size > 0) {
4569         const struct mf_field *field;
4570         enum ofperr error;
4571         bool hasmask;
4572
4573         error = nx_pull_header(payload, &field, &hasmask);
4574         if (!error) {
4575             bitmap_set1(hasmask ? masked.bm : exact.bm, field->id);
4576         } else if (error != OFPERR_OFPBMC_BAD_FIELD || !loose) {
4577             return error;
4578         }
4579     }
4580     if (exactp) {
4581         *exactp = exact;
4582     } else if (!bitmap_is_all_zeros(exact.bm, MFF_N_IDS)) {
4583         return OFPERR_OFPBMC_BAD_MASK;
4584     }
4585     if (maskedp) {
4586         *maskedp = masked;
4587     } else if (!bitmap_is_all_zeros(masked.bm, MFF_N_IDS)) {
4588         return OFPERR_OFPBMC_BAD_MASK;
4589     }
4590     return 0;
4591 }
4592
4593 /* Converts an OFPMP_TABLE_FEATURES request or reply in 'msg' into an abstract
4594  * ofputil_table_features in 'tf'.
4595  *
4596  * If 'loose' is true, this function ignores properties and values that it does
4597  * not understand, as a controller would want to do when interpreting
4598  * capabilities provided by a switch.  If 'loose' is false, this function
4599  * treats unknown properties and values as an error, as a switch would want to
4600  * do when interpreting a configuration request made by a controller.
4601  *
4602  * A single OpenFlow message can specify features for multiple tables.  Calling
4603  * this function multiple times for a single 'msg' iterates through the tables
4604  * in the message.  The caller must initially leave 'msg''s layer pointers null
4605  * and not modify them between calls.
4606  *
4607  * Returns 0 if successful, EOF if no tables were left in this 'msg', otherwise
4608  * a positive "enum ofperr" value. */
4609 int
4610 ofputil_decode_table_features(struct ofpbuf *msg,
4611                               struct ofputil_table_features *tf, bool loose)
4612 {
4613     const struct ofp_header *oh;
4614     struct ofp13_table_features *otf;
4615     struct ofpbuf properties;
4616     unsigned int len;
4617
4618     memset(tf, 0, sizeof *tf);
4619
4620     if (!msg->header) {
4621         ofpraw_pull_assert(msg);
4622     }
4623     oh = msg->header;
4624
4625     if (!msg->size) {
4626         return EOF;
4627     }
4628
4629     if (msg->size < sizeof *otf) {
4630         return OFPERR_OFPBPC_BAD_LEN;
4631     }
4632
4633     otf = msg->data;
4634     len = ntohs(otf->length);
4635     if (len < sizeof *otf || len % 8 || len > msg->size) {
4636         return OFPERR_OFPBPC_BAD_LEN;
4637     }
4638     ofpbuf_use_const(&properties, ofpbuf_pull(msg, len), len);
4639     ofpbuf_pull(&properties, sizeof *otf);
4640
4641     tf->table_id = otf->table_id;
4642     if (tf->table_id == OFPTT_ALL) {
4643         return OFPERR_OFPTFFC_BAD_TABLE;
4644     }
4645
4646     ovs_strlcpy(tf->name, otf->name, OFP_MAX_TABLE_NAME_LEN);
4647     tf->metadata_match = otf->metadata_match;
4648     tf->metadata_write = otf->metadata_write;
4649     tf->miss_config = OFPUTIL_TABLE_MISS_DEFAULT;
4650     if (oh->version >= OFP14_VERSION) {
4651         uint32_t caps = ntohl(otf->capabilities);
4652         tf->supports_eviction = (caps & OFPTC14_EVICTION) != 0;
4653         tf->supports_vacancy_events = (caps & OFPTC14_VACANCY_EVENTS) != 0;
4654     } else {
4655         tf->supports_eviction = -1;
4656         tf->supports_vacancy_events = -1;
4657     }
4658     tf->max_entries = ntohl(otf->max_entries);
4659
4660     while (properties.size > 0) {
4661         struct ofpbuf payload;
4662         enum ofperr error;
4663         uint16_t type;
4664
4665         error = pull_table_feature_property(&properties, &payload, &type);
4666         if (error) {
4667             return error;
4668         }
4669
4670         switch ((enum ofp13_table_feature_prop_type) type) {
4671         case OFPTFPT13_INSTRUCTIONS:
4672             error = parse_instruction_ids(&payload, loose,
4673                                           &tf->nonmiss.instructions);
4674             break;
4675         case OFPTFPT13_INSTRUCTIONS_MISS:
4676             error = parse_instruction_ids(&payload, loose,
4677                                           &tf->miss.instructions);
4678             break;
4679
4680         case OFPTFPT13_NEXT_TABLES:
4681             error = parse_table_features_next_table(&payload,
4682                                                     tf->nonmiss.next);
4683             break;
4684         case OFPTFPT13_NEXT_TABLES_MISS:
4685             error = parse_table_features_next_table(&payload, tf->miss.next);
4686             break;
4687
4688         case OFPTFPT13_WRITE_ACTIONS:
4689             error = parse_action_bitmap(&payload, oh->version,
4690                                         &tf->nonmiss.write.ofpacts);
4691             break;
4692         case OFPTFPT13_WRITE_ACTIONS_MISS:
4693             error = parse_action_bitmap(&payload, oh->version,
4694                                         &tf->miss.write.ofpacts);
4695             break;
4696
4697         case OFPTFPT13_APPLY_ACTIONS:
4698             error = parse_action_bitmap(&payload, oh->version,
4699                                         &tf->nonmiss.apply.ofpacts);
4700             break;
4701         case OFPTFPT13_APPLY_ACTIONS_MISS:
4702             error = parse_action_bitmap(&payload, oh->version,
4703                                         &tf->miss.apply.ofpacts);
4704             break;
4705
4706         case OFPTFPT13_MATCH:
4707             error = parse_oxms(&payload, loose, &tf->match, &tf->mask);
4708             break;
4709         case OFPTFPT13_WILDCARDS:
4710             error = parse_oxms(&payload, loose, &tf->wildcard, NULL);
4711             break;
4712
4713         case OFPTFPT13_WRITE_SETFIELD:
4714             error = parse_oxms(&payload, loose,
4715                                &tf->nonmiss.write.set_fields, NULL);
4716             break;
4717         case OFPTFPT13_WRITE_SETFIELD_MISS:
4718             error = parse_oxms(&payload, loose,
4719                                &tf->miss.write.set_fields, NULL);
4720             break;
4721         case OFPTFPT13_APPLY_SETFIELD:
4722             error = parse_oxms(&payload, loose,
4723                                &tf->nonmiss.apply.set_fields, NULL);
4724             break;
4725         case OFPTFPT13_APPLY_SETFIELD_MISS:
4726             error = parse_oxms(&payload, loose,
4727                                &tf->miss.apply.set_fields, NULL);
4728             break;
4729
4730         case OFPTFPT13_EXPERIMENTER:
4731         case OFPTFPT13_EXPERIMENTER_MISS:
4732         default:
4733             log_property(loose, "unknown table features property %"PRIu16,
4734                          type);
4735             error = loose ? 0 : OFPERR_OFPBPC_BAD_TYPE;
4736             break;
4737         }
4738         if (error) {
4739             return error;
4740         }
4741     }
4742
4743     /* Fix inconsistencies:
4744      *
4745      *     - Turn on 'match' bits that are set in 'mask', because maskable
4746      *       fields are matchable.
4747      *
4748      *     - Turn on 'wildcard' bits that are set in 'mask', because a field
4749      *       that is arbitrarily maskable can be wildcarded entirely.
4750      *
4751      *     - Turn off 'wildcard' bits that are not in 'match', because a field
4752      *       must be matchable for it to be meaningfully wildcarded. */
4753     bitmap_or(tf->match.bm, tf->mask.bm, MFF_N_IDS);
4754     bitmap_or(tf->wildcard.bm, tf->mask.bm, MFF_N_IDS);
4755     bitmap_and(tf->wildcard.bm, tf->match.bm, MFF_N_IDS);
4756
4757     return 0;
4758 }
4759
4760 /* Encodes and returns a request to obtain the table features of a switch.
4761  * The message is encoded for OpenFlow version 'ofp_version'. */
4762 struct ofpbuf *
4763 ofputil_encode_table_features_request(enum ofp_version ofp_version)
4764 {
4765     struct ofpbuf *request = NULL;
4766
4767     switch (ofp_version) {
4768     case OFP10_VERSION:
4769     case OFP11_VERSION:
4770     case OFP12_VERSION:
4771         ovs_fatal(0, "dump-table-features needs OpenFlow 1.3 or later "
4772                      "(\'-O OpenFlow13\')");
4773     case OFP13_VERSION:
4774     case OFP14_VERSION:
4775     case OFP15_VERSION:
4776         request = ofpraw_alloc(OFPRAW_OFPST13_TABLE_FEATURES_REQUEST,
4777                                ofp_version, 0);
4778         break;
4779     default:
4780         OVS_NOT_REACHED();
4781     }
4782
4783     return request;
4784 }
4785
4786 static void
4787 put_fields_property(struct ofpbuf *reply,
4788                     const struct mf_bitmap *fields,
4789                     const struct mf_bitmap *masks,
4790                     enum ofp13_table_feature_prop_type property,
4791                     enum ofp_version version)
4792 {
4793     size_t start_ofs;
4794     int field;
4795
4796     start_ofs = start_property(reply, property);
4797     BITMAP_FOR_EACH_1 (field, MFF_N_IDS, fields->bm) {
4798         nx_put_header(reply, field, version,
4799                       masks && bitmap_is_set(masks->bm, field));
4800     }
4801     end_property(reply, start_ofs);
4802 }
4803
4804 static void
4805 put_table_action_features(struct ofpbuf *reply,
4806                           const struct ofputil_table_action_features *taf,
4807                           enum ofp13_table_feature_prop_type actions_type,
4808                           enum ofp13_table_feature_prop_type set_fields_type,
4809                           int miss_offset, enum ofp_version version)
4810 {
4811     size_t start_ofs;
4812
4813     start_ofs = start_property(reply, actions_type + miss_offset);
4814     put_bitmap_properties(reply,
4815                           ntohl(ofpact_bitmap_to_openflow(taf->ofpacts,
4816                                                           version)));
4817     end_property(reply, start_ofs);
4818
4819     put_fields_property(reply, &taf->set_fields, NULL,
4820                         set_fields_type + miss_offset, version);
4821 }
4822
4823 static void
4824 put_table_instruction_features(
4825     struct ofpbuf *reply, const struct ofputil_table_instruction_features *tif,
4826     int miss_offset, enum ofp_version version)
4827 {
4828     size_t start_ofs;
4829     uint8_t table_id;
4830
4831     start_ofs = start_property(reply, OFPTFPT13_INSTRUCTIONS + miss_offset);
4832     put_bitmap_properties(reply,
4833                           ntohl(ovsinst_bitmap_to_openflow(tif->instructions,
4834                                                            version)));
4835     end_property(reply, start_ofs);
4836
4837     start_ofs = start_property(reply, OFPTFPT13_NEXT_TABLES + miss_offset);
4838     BITMAP_FOR_EACH_1 (table_id, 255, tif->next) {
4839         ofpbuf_put(reply, &table_id, 1);
4840     }
4841     end_property(reply, start_ofs);
4842
4843     put_table_action_features(reply, &tif->write,
4844                               OFPTFPT13_WRITE_ACTIONS,
4845                               OFPTFPT13_WRITE_SETFIELD, miss_offset, version);
4846     put_table_action_features(reply, &tif->apply,
4847                               OFPTFPT13_APPLY_ACTIONS,
4848                               OFPTFPT13_APPLY_SETFIELD, miss_offset, version);
4849 }
4850
4851 void
4852 ofputil_append_table_features_reply(const struct ofputil_table_features *tf,
4853                                     struct ovs_list *replies)
4854 {
4855     struct ofpbuf *reply = ofpbuf_from_list(list_back(replies));
4856     enum ofp_version version = ofpmp_version(replies);
4857     size_t start_ofs = reply->size;
4858     struct ofp13_table_features *otf;
4859
4860     otf = ofpbuf_put_zeros(reply, sizeof *otf);
4861     otf->table_id = tf->table_id;
4862     ovs_strlcpy(otf->name, tf->name, sizeof otf->name);
4863     otf->metadata_match = tf->metadata_match;
4864     otf->metadata_write = tf->metadata_write;
4865     if (version >= OFP14_VERSION) {
4866         if (tf->supports_eviction) {
4867             otf->capabilities |= htonl(OFPTC14_EVICTION);
4868         }
4869         if (tf->supports_vacancy_events) {
4870             otf->capabilities |= htonl(OFPTC14_VACANCY_EVENTS);
4871         }
4872     }
4873     otf->max_entries = htonl(tf->max_entries);
4874
4875     put_table_instruction_features(reply, &tf->nonmiss, 0, version);
4876     put_table_instruction_features(reply, &tf->miss, 1, version);
4877
4878     put_fields_property(reply, &tf->match, &tf->mask,
4879                         OFPTFPT13_MATCH, version);
4880     put_fields_property(reply, &tf->wildcard, NULL,
4881                         OFPTFPT13_WILDCARDS, version);
4882
4883     otf = ofpbuf_at_assert(reply, start_ofs, sizeof *otf);
4884     otf->length = htons(reply->size - start_ofs);
4885     ofpmp_postappend(replies, start_ofs);
4886 }
4887
4888 static enum ofperr
4889 parse_table_desc_eviction_property(struct ofpbuf *property,
4890                                    struct ofputil_table_desc *td)
4891 {
4892     struct ofp14_table_mod_prop_eviction *ote = property->data;
4893
4894     if (property->size != sizeof *ote) {
4895         return OFPERR_OFPBPC_BAD_LEN;
4896     }
4897
4898     td->eviction_flags = ntohl(ote->flags);
4899     return 0;
4900 }
4901
4902 /* Decodes the next OpenFlow "table desc" message (of possibly several) from
4903  * 'msg' into an abstract form in '*td'.  Returns 0 if successful, EOF if the
4904  * last "table desc" in 'msg' was already decoded, otherwise an OFPERR_*
4905  * value. */
4906 int
4907 ofputil_decode_table_desc(struct ofpbuf *msg,
4908                           struct ofputil_table_desc *td,
4909                           enum ofp_version version)
4910 {
4911     struct ofp14_table_desc *otd;
4912     struct ofpbuf properties;
4913     size_t length;
4914
4915     memset(td, 0, sizeof *td);
4916
4917     if (!msg->header) {
4918         ofpraw_pull_assert(msg);
4919     }
4920
4921     if (!msg->size) {
4922         return EOF;
4923     }
4924
4925     otd = ofpbuf_try_pull(msg, sizeof *otd);
4926     if (!otd) {
4927         VLOG_WARN_RL(&bad_ofmsg_rl, "OFP14_TABLE_DESC reply has %"PRIu32" "
4928                      "leftover bytes at end", msg->size);
4929         return OFPERR_OFPBRC_BAD_LEN;
4930     }
4931
4932     td->table_id = otd->table_id;
4933     length = ntohs(otd->length);
4934     if (length < sizeof *otd || length - sizeof *otd > msg->size) {
4935         VLOG_WARN_RL(&bad_ofmsg_rl, "OFP14_TABLE_DESC reply claims invalid "
4936                      "length %"PRIuSIZE, length);
4937         return OFPERR_OFPBRC_BAD_LEN;
4938     }
4939     length -= sizeof *otd;
4940     ofpbuf_use_const(&properties, ofpbuf_pull(msg, length), length);
4941
4942     td->eviction = ofputil_decode_table_eviction(otd->config, version);
4943     td->eviction_flags = UINT32_MAX;
4944
4945     while (properties.size > 0) {
4946         struct ofpbuf payload;
4947         enum ofperr error;
4948         uint16_t type;
4949
4950         error = ofputil_pull_property(&properties, &payload, &type);
4951         if (error) {
4952             return error;
4953         }
4954
4955         switch (type) {
4956         case OFPTMPT14_EVICTION:
4957             error = parse_table_desc_eviction_property(&payload, td);
4958             break;
4959
4960         default:
4961             log_property(true, "unknown table_desc property %"PRIu16, type);
4962             error = 0;
4963             break;
4964         }
4965
4966         if (error) {
4967             return error;
4968         }
4969     }
4970
4971     return 0;
4972 }
4973
4974 /* Encodes and returns a request to obtain description of tables of a switch.
4975  * The message is encoded for OpenFlow version 'ofp_version'. */
4976 struct ofpbuf *
4977 ofputil_encode_table_desc_request(enum ofp_version ofp_version)
4978 {
4979     struct ofpbuf *request = NULL;
4980
4981     if (ofp_version >= OFP14_VERSION) {
4982         request = ofpraw_alloc(OFPRAW_OFPST14_TABLE_DESC_REQUEST,
4983                                ofp_version, 0);
4984     } else {
4985         ovs_fatal(0, "dump-table-desc needs OpenFlow 1.4 or later "
4986                   "(\'-O OpenFlow14\')");
4987     }
4988
4989     return request;
4990 }
4991
4992 /* Function to append Table desc information in a reply list. */
4993 void
4994 ofputil_append_table_desc_reply(const struct ofputil_table_desc *td,
4995                                 struct ovs_list *replies,
4996                                 enum ofp_version version)
4997 {
4998     struct ofpbuf *reply = ofpbuf_from_list(list_back(replies));
4999     size_t start_otd;
5000     struct ofp14_table_desc *otd;
5001
5002     start_otd = reply->size;
5003     ofpbuf_put_zeros(reply, sizeof *otd);
5004     if (td->eviction_flags != UINT32_MAX) {
5005         struct ofp14_table_mod_prop_eviction *ote;
5006
5007         ote = ofpbuf_put_zeros(reply, sizeof *ote);
5008         ote->type = htons(OFPTMPT14_EVICTION);
5009         ote->length = htons(sizeof *ote);
5010         ote->flags = htonl(td->eviction_flags);
5011     }
5012
5013     otd = ofpbuf_at_assert(reply, start_otd, sizeof *otd);
5014     otd->length = htons(reply->size - start_otd);
5015     otd->table_id = td->table_id;
5016     otd->config = ofputil_encode_table_config(OFPUTIL_TABLE_MISS_DEFAULT,
5017                                               td->eviction, version);
5018     ofpmp_postappend(replies, start_otd);
5019 }
5020
5021 static enum ofperr
5022 parse_table_mod_eviction_property(struct ofpbuf *property,
5023                                   struct ofputil_table_mod *tm)
5024 {
5025     struct ofp14_table_mod_prop_eviction *ote = property->data;
5026
5027     if (property->size != sizeof *ote) {
5028         return OFPERR_OFPBPC_BAD_LEN;
5029     }
5030
5031     tm->eviction_flags = ntohl(ote->flags);
5032     return 0;
5033 }
5034
5035 /* Given 'config', taken from an OpenFlow 'version' message that specifies
5036  * table configuration (a table mod, table stats, or table features message),
5037  * returns the table eviction configuration that it specifies.
5038  *
5039  * Only OpenFlow 1.4 and later specify table eviction configuration this way,
5040  * so for other 'version' values this function always returns
5041  * OFPUTIL_TABLE_EVICTION_DEFAULT. */
5042 static enum ofputil_table_eviction
5043 ofputil_decode_table_eviction(ovs_be32 config, enum ofp_version version)
5044 {
5045     return (version < OFP14_VERSION ? OFPUTIL_TABLE_EVICTION_DEFAULT
5046             : config & htonl(OFPTC14_EVICTION) ? OFPUTIL_TABLE_EVICTION_ON
5047             : OFPUTIL_TABLE_EVICTION_OFF);
5048 }
5049
5050 /* Returns a bitmap of OFPTC* values suitable for 'config' fields in various
5051  * OpenFlow messages of the given 'version', based on the provided 'miss' and
5052  * 'eviction' values. */
5053 static ovs_be32
5054 ofputil_encode_table_config(enum ofputil_table_miss miss,
5055                             enum ofputil_table_eviction eviction,
5056                             enum ofp_version version)
5057 {
5058     /* See the section "OFPTC_* Table Configuration" in DESIGN.md for more
5059      * information on the crazy evolution of this field. */
5060     switch (version) {
5061     case OFP10_VERSION:
5062         /* OpenFlow 1.0 didn't have such a field, any value ought to do. */
5063         return htonl(0);
5064
5065     case OFP11_VERSION:
5066     case OFP12_VERSION:
5067         /* OpenFlow 1.1 and 1.2 define only OFPTC11_TABLE_MISS_*. */
5068         switch (miss) {
5069         case OFPUTIL_TABLE_MISS_DEFAULT:
5070             /* Really this shouldn't be used for encoding (the caller should
5071              * provide a specific value) but I can't imagine that defaulting to
5072              * the fall-through case here will hurt. */
5073         case OFPUTIL_TABLE_MISS_CONTROLLER:
5074         default:
5075             return htonl(OFPTC11_TABLE_MISS_CONTROLLER);
5076         case OFPUTIL_TABLE_MISS_CONTINUE:
5077             return htonl(OFPTC11_TABLE_MISS_CONTINUE);
5078         case OFPUTIL_TABLE_MISS_DROP:
5079             return htonl(OFPTC11_TABLE_MISS_DROP);
5080         }
5081         OVS_NOT_REACHED();
5082
5083     case OFP13_VERSION:
5084         /* OpenFlow 1.3 removed OFPTC11_TABLE_MISS_* and didn't define any new
5085          * flags, so this is correct. */
5086         return htonl(0);
5087
5088     case OFP14_VERSION:
5089     case OFP15_VERSION:
5090         /* OpenFlow 1.4 introduced OFPTC14_EVICTION and OFPTC14_VACANCY_EVENTS
5091          * and we don't support the latter yet. */
5092         return htonl(eviction == OFPUTIL_TABLE_EVICTION_ON
5093                      ? OFPTC14_EVICTION : 0);
5094     }
5095
5096     OVS_NOT_REACHED();
5097 }
5098
5099 /* Given 'config', taken from an OpenFlow 'version' message that specifies
5100  * table configuration (a table mod, table stats, or table features message),
5101  * returns the table miss configuration that it specifies.
5102  *
5103  * Only OpenFlow 1.1 and 1.2 specify table miss configurations this way, so for
5104  * other 'version' values this function always returns
5105  * OFPUTIL_TABLE_MISS_DEFAULT. */
5106 static enum ofputil_table_miss
5107 ofputil_decode_table_miss(ovs_be32 config_, enum ofp_version version)
5108 {
5109     uint32_t config = ntohl(config_);
5110
5111     if (version == OFP11_VERSION || version == OFP12_VERSION) {
5112         switch (config & OFPTC11_TABLE_MISS_MASK) {
5113         case OFPTC11_TABLE_MISS_CONTROLLER:
5114             return OFPUTIL_TABLE_MISS_CONTROLLER;
5115
5116         case OFPTC11_TABLE_MISS_CONTINUE:
5117             return OFPUTIL_TABLE_MISS_CONTINUE;
5118
5119         case OFPTC11_TABLE_MISS_DROP:
5120             return OFPUTIL_TABLE_MISS_DROP;
5121
5122         default:
5123             VLOG_WARN_RL(&bad_ofmsg_rl, "bad table miss config %d", config);
5124             return OFPUTIL_TABLE_MISS_CONTROLLER;
5125         }
5126     } else {
5127         return OFPUTIL_TABLE_MISS_DEFAULT;
5128     }
5129 }
5130
5131 /* Decodes the OpenFlow "table mod" message in '*oh' into an abstract form in
5132  * '*pm'.  Returns 0 if successful, otherwise an OFPERR_* value. */
5133 enum ofperr
5134 ofputil_decode_table_mod(const struct ofp_header *oh,
5135                          struct ofputil_table_mod *pm)
5136 {
5137     enum ofpraw raw;
5138     struct ofpbuf b;
5139
5140     memset(pm, 0, sizeof *pm);
5141     pm->miss = OFPUTIL_TABLE_MISS_DEFAULT;
5142     pm->eviction = OFPUTIL_TABLE_EVICTION_DEFAULT;
5143     pm->eviction_flags = UINT32_MAX;
5144     ofpbuf_use_const(&b, oh, ntohs(oh->length));
5145     raw = ofpraw_pull_assert(&b);
5146
5147     if (raw == OFPRAW_OFPT11_TABLE_MOD) {
5148         const struct ofp11_table_mod *otm = b.data;
5149
5150         pm->table_id = otm->table_id;
5151         pm->miss = ofputil_decode_table_miss(otm->config, oh->version);
5152     } else if (raw == OFPRAW_OFPT14_TABLE_MOD) {
5153         const struct ofp14_table_mod *otm = ofpbuf_pull(&b, sizeof *otm);
5154
5155         pm->table_id = otm->table_id;
5156         pm->miss = ofputil_decode_table_miss(otm->config, oh->version);
5157         pm->eviction = ofputil_decode_table_eviction(otm->config, oh->version);
5158         while (b.size > 0) {
5159             struct ofpbuf property;
5160             enum ofperr error;
5161             uint16_t type;
5162
5163             error = ofputil_pull_property(&b, &property, &type);
5164             if (error) {
5165                 return error;
5166             }
5167
5168             switch (type) {
5169             case OFPTMPT14_EVICTION:
5170                 error = parse_table_mod_eviction_property(&property, pm);
5171                 break;
5172
5173             default:
5174                 error = OFPERR_OFPBRC_BAD_TYPE;
5175                 break;
5176             }
5177
5178             if (error) {
5179                 return error;
5180             }
5181         }
5182     } else {
5183         return OFPERR_OFPBRC_BAD_TYPE;
5184     }
5185
5186     return 0;
5187 }
5188
5189 /* Converts the abstract form of a "table mod" message in '*tm' into an
5190  * OpenFlow message suitable for 'protocol', and returns that encoded form in a
5191  * buffer owned by the caller. */
5192 struct ofpbuf *
5193 ofputil_encode_table_mod(const struct ofputil_table_mod *tm,
5194                         enum ofputil_protocol protocol)
5195 {
5196     enum ofp_version ofp_version = ofputil_protocol_to_ofp_version(protocol);
5197     struct ofpbuf *b;
5198
5199     switch (ofp_version) {
5200     case OFP10_VERSION: {
5201         ovs_fatal(0, "table mod needs OpenFlow 1.1 or later "
5202                      "(\'-O OpenFlow11\')");
5203         break;
5204     }
5205     case OFP11_VERSION:
5206     case OFP12_VERSION:
5207     case OFP13_VERSION: {
5208         struct ofp11_table_mod *otm;
5209
5210         b = ofpraw_alloc(OFPRAW_OFPT11_TABLE_MOD, ofp_version, 0);
5211         otm = ofpbuf_put_zeros(b, sizeof *otm);
5212         otm->table_id = tm->table_id;
5213         otm->config = ofputil_encode_table_config(tm->miss, tm->eviction,
5214                                                   ofp_version);
5215         break;
5216     }
5217     case OFP14_VERSION:
5218     case OFP15_VERSION: {
5219         struct ofp14_table_mod *otm;
5220         struct ofp14_table_mod_prop_eviction *ote;
5221
5222         b = ofpraw_alloc(OFPRAW_OFPT14_TABLE_MOD, ofp_version, 0);
5223         otm = ofpbuf_put_zeros(b, sizeof *otm);
5224         otm->table_id = tm->table_id;
5225         otm->config = ofputil_encode_table_config(tm->miss, tm->eviction,
5226                                                   ofp_version);
5227
5228         if (tm->eviction_flags != UINT32_MAX) {
5229             ote = ofpbuf_put_zeros(b, sizeof *ote);
5230             ote->type = htons(OFPTMPT14_EVICTION);
5231             ote->length = htons(sizeof *ote);
5232             ote->flags = htonl(tm->eviction_flags);
5233         }
5234         break;
5235     }
5236     default:
5237         OVS_NOT_REACHED();
5238     }
5239
5240     return b;
5241 }
5242 \f
5243 /* ofputil_role_request */
5244
5245 /* Decodes the OpenFlow "role request" or "role reply" message in '*oh' into
5246  * an abstract form in '*rr'.  Returns 0 if successful, otherwise an
5247  * OFPERR_* value. */
5248 enum ofperr
5249 ofputil_decode_role_message(const struct ofp_header *oh,
5250                             struct ofputil_role_request *rr)
5251 {
5252     struct ofpbuf b;
5253     enum ofpraw raw;
5254
5255     ofpbuf_use_const(&b, oh, ntohs(oh->length));
5256     raw = ofpraw_pull_assert(&b);
5257
5258     if (raw == OFPRAW_OFPT12_ROLE_REQUEST ||
5259         raw == OFPRAW_OFPT12_ROLE_REPLY) {
5260         const struct ofp12_role_request *orr = b.msg;
5261
5262         if (orr->role != htonl(OFPCR12_ROLE_NOCHANGE) &&
5263             orr->role != htonl(OFPCR12_ROLE_EQUAL) &&
5264             orr->role != htonl(OFPCR12_ROLE_MASTER) &&
5265             orr->role != htonl(OFPCR12_ROLE_SLAVE)) {
5266             return OFPERR_OFPRRFC_BAD_ROLE;
5267         }
5268
5269         rr->role = ntohl(orr->role);
5270         if (raw == OFPRAW_OFPT12_ROLE_REQUEST
5271             ? orr->role == htonl(OFPCR12_ROLE_NOCHANGE)
5272             : orr->generation_id == OVS_BE64_MAX) {
5273             rr->have_generation_id = false;
5274             rr->generation_id = 0;
5275         } else {
5276             rr->have_generation_id = true;
5277             rr->generation_id = ntohll(orr->generation_id);
5278         }
5279     } else if (raw == OFPRAW_NXT_ROLE_REQUEST ||
5280                raw == OFPRAW_NXT_ROLE_REPLY) {
5281         const struct nx_role_request *nrr = b.msg;
5282
5283         BUILD_ASSERT(NX_ROLE_OTHER + 1 == OFPCR12_ROLE_EQUAL);
5284         BUILD_ASSERT(NX_ROLE_MASTER + 1 == OFPCR12_ROLE_MASTER);
5285         BUILD_ASSERT(NX_ROLE_SLAVE + 1 == OFPCR12_ROLE_SLAVE);
5286
5287         if (nrr->role != htonl(NX_ROLE_OTHER) &&
5288             nrr->role != htonl(NX_ROLE_MASTER) &&
5289             nrr->role != htonl(NX_ROLE_SLAVE)) {
5290             return OFPERR_OFPRRFC_BAD_ROLE;
5291         }
5292
5293         rr->role = ntohl(nrr->role) + 1;
5294         rr->have_generation_id = false;
5295         rr->generation_id = 0;
5296     } else {
5297         OVS_NOT_REACHED();
5298     }
5299
5300     return 0;
5301 }
5302
5303 /* Returns an encoded form of a role reply suitable for the "request" in a
5304  * buffer owned by the caller. */
5305 struct ofpbuf *
5306 ofputil_encode_role_reply(const struct ofp_header *request,
5307                           const struct ofputil_role_request *rr)
5308 {
5309     struct ofpbuf *buf;
5310     enum ofpraw raw;
5311
5312     raw = ofpraw_decode_assert(request);
5313     if (raw == OFPRAW_OFPT12_ROLE_REQUEST) {
5314         struct ofp12_role_request *orr;
5315
5316         buf = ofpraw_alloc_reply(OFPRAW_OFPT12_ROLE_REPLY, request, 0);
5317         orr = ofpbuf_put_zeros(buf, sizeof *orr);
5318
5319         orr->role = htonl(rr->role);
5320         orr->generation_id = htonll(rr->have_generation_id
5321                                     ? rr->generation_id
5322                                     : UINT64_MAX);
5323     } else if (raw == OFPRAW_NXT_ROLE_REQUEST) {
5324         struct nx_role_request *nrr;
5325
5326         BUILD_ASSERT(NX_ROLE_OTHER == OFPCR12_ROLE_EQUAL - 1);
5327         BUILD_ASSERT(NX_ROLE_MASTER == OFPCR12_ROLE_MASTER - 1);
5328         BUILD_ASSERT(NX_ROLE_SLAVE == OFPCR12_ROLE_SLAVE - 1);
5329
5330         buf = ofpraw_alloc_reply(OFPRAW_NXT_ROLE_REPLY, request, 0);
5331         nrr = ofpbuf_put_zeros(buf, sizeof *nrr);
5332         nrr->role = htonl(rr->role - 1);
5333     } else {
5334         OVS_NOT_REACHED();
5335     }
5336
5337     return buf;
5338 }
5339 \f
5340 /* Encodes "role status" message 'status' for sending in the given
5341  * 'protocol'.  Returns the role status message, if 'protocol' supports them,
5342  * otherwise a null pointer. */
5343 struct ofpbuf *
5344 ofputil_encode_role_status(const struct ofputil_role_status *status,
5345                            enum ofputil_protocol protocol)
5346 {
5347     enum ofp_version version;
5348
5349     version = ofputil_protocol_to_ofp_version(protocol);
5350     if (version >= OFP14_VERSION) {
5351         struct ofp14_role_status *rstatus;
5352         struct ofpbuf *buf;
5353
5354         buf = ofpraw_alloc_xid(OFPRAW_OFPT14_ROLE_STATUS, version, htonl(0),
5355                                0);
5356         rstatus = ofpbuf_put_zeros(buf, sizeof *rstatus);
5357         rstatus->role = htonl(status->role);
5358         rstatus->reason = status->reason;
5359         rstatus->generation_id = htonll(status->generation_id);
5360
5361         return buf;
5362     } else {
5363         return NULL;
5364     }
5365 }
5366
5367 enum ofperr
5368 ofputil_decode_role_status(const struct ofp_header *oh,
5369                            struct ofputil_role_status *rs)
5370 {
5371     struct ofpbuf b;
5372     enum ofpraw raw;
5373     const struct ofp14_role_status *r;
5374
5375     ofpbuf_use_const(&b, oh, ntohs(oh->length));
5376     raw = ofpraw_pull_assert(&b);
5377     ovs_assert(raw == OFPRAW_OFPT14_ROLE_STATUS);
5378
5379     r = b.msg;
5380     if (r->role != htonl(OFPCR12_ROLE_NOCHANGE) &&
5381         r->role != htonl(OFPCR12_ROLE_EQUAL) &&
5382         r->role != htonl(OFPCR12_ROLE_MASTER) &&
5383         r->role != htonl(OFPCR12_ROLE_SLAVE)) {
5384         return OFPERR_OFPRRFC_BAD_ROLE;
5385     }
5386
5387     rs->role = ntohl(r->role);
5388     rs->generation_id = ntohll(r->generation_id);
5389     rs->reason = r->reason;
5390
5391     return 0;
5392 }
5393
5394 /* Table stats. */
5395
5396 /* OpenFlow 1.0 and 1.1 don't distinguish between a field that cannot be
5397  * matched and a field that must be wildcarded.  This function returns a bitmap
5398  * that contains both kinds of fields. */
5399 static struct mf_bitmap
5400 wild_or_nonmatchable_fields(const struct ofputil_table_features *features)
5401 {
5402     struct mf_bitmap wc = features->match;
5403     bitmap_not(wc.bm, MFF_N_IDS);
5404     bitmap_or(wc.bm, features->wildcard.bm, MFF_N_IDS);
5405     return wc;
5406 }
5407
5408 struct ofp10_wc_map {
5409     enum ofp10_flow_wildcards wc10;
5410     enum mf_field_id mf;
5411 };
5412
5413 static const struct ofp10_wc_map ofp10_wc_map[] = {
5414     { OFPFW10_IN_PORT,     MFF_IN_PORT },
5415     { OFPFW10_DL_VLAN,     MFF_VLAN_VID },
5416     { OFPFW10_DL_SRC,      MFF_ETH_SRC },
5417     { OFPFW10_DL_DST,      MFF_ETH_DST},
5418     { OFPFW10_DL_TYPE,     MFF_ETH_TYPE },
5419     { OFPFW10_NW_PROTO,    MFF_IP_PROTO },
5420     { OFPFW10_TP_SRC,      MFF_TCP_SRC },
5421     { OFPFW10_TP_DST,      MFF_TCP_DST },
5422     { OFPFW10_NW_SRC_MASK, MFF_IPV4_SRC },
5423     { OFPFW10_NW_DST_MASK, MFF_IPV4_DST },
5424     { OFPFW10_DL_VLAN_PCP, MFF_VLAN_PCP },
5425     { OFPFW10_NW_TOS,      MFF_IP_DSCP },
5426 };
5427
5428 static ovs_be32
5429 mf_bitmap_to_of10(const struct mf_bitmap *fields)
5430 {
5431     const struct ofp10_wc_map *p;
5432     uint32_t wc10 = 0;
5433
5434     for (p = ofp10_wc_map; p < &ofp10_wc_map[ARRAY_SIZE(ofp10_wc_map)]; p++) {
5435         if (bitmap_is_set(fields->bm, p->mf)) {
5436             wc10 |= p->wc10;
5437         }
5438     }
5439     return htonl(wc10);
5440 }
5441
5442 static struct mf_bitmap
5443 mf_bitmap_from_of10(ovs_be32 wc10_)
5444 {
5445     struct mf_bitmap fields = MF_BITMAP_INITIALIZER;
5446     const struct ofp10_wc_map *p;
5447     uint32_t wc10 = ntohl(wc10_);
5448
5449     for (p = ofp10_wc_map; p < &ofp10_wc_map[ARRAY_SIZE(ofp10_wc_map)]; p++) {
5450         if (wc10 & p->wc10) {
5451             bitmap_set1(fields.bm, p->mf);
5452         }
5453     }
5454     return fields;
5455 }
5456
5457 static void
5458 ofputil_put_ofp10_table_stats(const struct ofputil_table_stats *stats,
5459                               const struct ofputil_table_features *features,
5460                               struct ofpbuf *buf)
5461 {
5462     struct mf_bitmap wc = wild_or_nonmatchable_fields(features);
5463     struct ofp10_table_stats *out;
5464
5465     out = ofpbuf_put_zeros(buf, sizeof *out);
5466     out->table_id = features->table_id;
5467     ovs_strlcpy(out->name, features->name, sizeof out->name);
5468     out->wildcards = mf_bitmap_to_of10(&wc);
5469     out->max_entries = htonl(features->max_entries);
5470     out->active_count = htonl(stats->active_count);
5471     put_32aligned_be64(&out->lookup_count, htonll(stats->lookup_count));
5472     put_32aligned_be64(&out->matched_count, htonll(stats->matched_count));
5473 }
5474
5475 struct ofp11_wc_map {
5476     enum ofp11_flow_match_fields wc11;
5477     enum mf_field_id mf;
5478 };
5479
5480 static const struct ofp11_wc_map ofp11_wc_map[] = {
5481     { OFPFMF11_IN_PORT,     MFF_IN_PORT },
5482     { OFPFMF11_DL_VLAN,     MFF_VLAN_VID },
5483     { OFPFMF11_DL_VLAN_PCP, MFF_VLAN_PCP },
5484     { OFPFMF11_DL_TYPE,     MFF_ETH_TYPE },
5485     { OFPFMF11_NW_TOS,      MFF_IP_DSCP },
5486     { OFPFMF11_NW_PROTO,    MFF_IP_PROTO },
5487     { OFPFMF11_TP_SRC,      MFF_TCP_SRC },
5488     { OFPFMF11_TP_DST,      MFF_TCP_DST },
5489     { OFPFMF11_MPLS_LABEL,  MFF_MPLS_LABEL },
5490     { OFPFMF11_MPLS_TC,     MFF_MPLS_TC },
5491     /* I don't know what OFPFMF11_TYPE means. */
5492     { OFPFMF11_DL_SRC,      MFF_ETH_SRC },
5493     { OFPFMF11_DL_DST,      MFF_ETH_DST },
5494     { OFPFMF11_NW_SRC,      MFF_IPV4_SRC },
5495     { OFPFMF11_NW_DST,      MFF_IPV4_DST },
5496     { OFPFMF11_METADATA,    MFF_METADATA },
5497 };
5498
5499 static ovs_be32
5500 mf_bitmap_to_of11(const struct mf_bitmap *fields)
5501 {
5502     const struct ofp11_wc_map *p;
5503     uint32_t wc11 = 0;
5504
5505     for (p = ofp11_wc_map; p < &ofp11_wc_map[ARRAY_SIZE(ofp11_wc_map)]; p++) {
5506         if (bitmap_is_set(fields->bm, p->mf)) {
5507             wc11 |= p->wc11;
5508         }
5509     }
5510     return htonl(wc11);
5511 }
5512
5513 static struct mf_bitmap
5514 mf_bitmap_from_of11(ovs_be32 wc11_)
5515 {
5516     struct mf_bitmap fields = MF_BITMAP_INITIALIZER;
5517     const struct ofp11_wc_map *p;
5518     uint32_t wc11 = ntohl(wc11_);
5519
5520     for (p = ofp11_wc_map; p < &ofp11_wc_map[ARRAY_SIZE(ofp11_wc_map)]; p++) {
5521         if (wc11 & p->wc11) {
5522             bitmap_set1(fields.bm, p->mf);
5523         }
5524     }
5525     return fields;
5526 }
5527
5528 static void
5529 ofputil_put_ofp11_table_stats(const struct ofputil_table_stats *stats,
5530                               const struct ofputil_table_features *features,
5531                               struct ofpbuf *buf)
5532 {
5533     struct mf_bitmap wc = wild_or_nonmatchable_fields(features);
5534     struct ofp11_table_stats *out;
5535
5536     out = ofpbuf_put_zeros(buf, sizeof *out);
5537     out->table_id = features->table_id;
5538     ovs_strlcpy(out->name, features->name, sizeof out->name);
5539     out->wildcards = mf_bitmap_to_of11(&wc);
5540     out->match = mf_bitmap_to_of11(&features->match);
5541     out->instructions = ovsinst_bitmap_to_openflow(
5542         features->nonmiss.instructions, OFP11_VERSION);
5543     out->write_actions = ofpact_bitmap_to_openflow(
5544         features->nonmiss.write.ofpacts, OFP11_VERSION);
5545     out->apply_actions = ofpact_bitmap_to_openflow(
5546         features->nonmiss.apply.ofpacts, OFP11_VERSION);
5547     out->config = htonl(features->miss_config);
5548     out->max_entries = htonl(features->max_entries);
5549     out->active_count = htonl(stats->active_count);
5550     out->lookup_count = htonll(stats->lookup_count);
5551     out->matched_count = htonll(stats->matched_count);
5552 }
5553
5554 static void
5555 ofputil_put_ofp12_table_stats(const struct ofputil_table_stats *stats,
5556                               const struct ofputil_table_features *features,
5557                               struct ofpbuf *buf)
5558 {
5559     struct ofp12_table_stats *out;
5560
5561     out = ofpbuf_put_zeros(buf, sizeof *out);
5562     out->table_id = features->table_id;
5563     ovs_strlcpy(out->name, features->name, sizeof out->name);
5564     out->match = oxm_bitmap_from_mf_bitmap(&features->match, OFP12_VERSION);
5565     out->wildcards = oxm_bitmap_from_mf_bitmap(&features->wildcard,
5566                                              OFP12_VERSION);
5567     out->write_actions = ofpact_bitmap_to_openflow(
5568         features->nonmiss.write.ofpacts, OFP12_VERSION);
5569     out->apply_actions = ofpact_bitmap_to_openflow(
5570         features->nonmiss.apply.ofpacts, OFP12_VERSION);
5571     out->write_setfields = oxm_bitmap_from_mf_bitmap(
5572         &features->nonmiss.write.set_fields, OFP12_VERSION);
5573     out->apply_setfields = oxm_bitmap_from_mf_bitmap(
5574         &features->nonmiss.apply.set_fields, OFP12_VERSION);
5575     out->metadata_match = features->metadata_match;
5576     out->metadata_write = features->metadata_write;
5577     out->instructions = ovsinst_bitmap_to_openflow(
5578         features->nonmiss.instructions, OFP12_VERSION);
5579     out->config = ofputil_encode_table_config(features->miss_config,
5580                                               OFPUTIL_TABLE_EVICTION_DEFAULT,
5581                                               OFP12_VERSION);
5582     out->max_entries = htonl(features->max_entries);
5583     out->active_count = htonl(stats->active_count);
5584     out->lookup_count = htonll(stats->lookup_count);
5585     out->matched_count = htonll(stats->matched_count);
5586 }
5587
5588 static void
5589 ofputil_put_ofp13_table_stats(const struct ofputil_table_stats *stats,
5590                               struct ofpbuf *buf)
5591 {
5592     struct ofp13_table_stats *out;
5593
5594     out = ofpbuf_put_zeros(buf, sizeof *out);
5595     out->table_id = stats->table_id;
5596     out->active_count = htonl(stats->active_count);
5597     out->lookup_count = htonll(stats->lookup_count);
5598     out->matched_count = htonll(stats->matched_count);
5599 }
5600
5601 struct ofpbuf *
5602 ofputil_encode_table_stats_reply(const struct ofp_header *request)
5603 {
5604     return ofpraw_alloc_stats_reply(request, 0);
5605 }
5606
5607 void
5608 ofputil_append_table_stats_reply(struct ofpbuf *reply,
5609                                  const struct ofputil_table_stats *stats,
5610                                  const struct ofputil_table_features *features)
5611 {
5612     struct ofp_header *oh = reply->header;
5613
5614     ovs_assert(stats->table_id == features->table_id);
5615
5616     switch ((enum ofp_version) oh->version) {
5617     case OFP10_VERSION:
5618         ofputil_put_ofp10_table_stats(stats, features, reply);
5619         break;
5620
5621     case OFP11_VERSION:
5622         ofputil_put_ofp11_table_stats(stats, features, reply);
5623         break;
5624
5625     case OFP12_VERSION:
5626         ofputil_put_ofp12_table_stats(stats, features, reply);
5627         break;
5628
5629     case OFP13_VERSION:
5630     case OFP14_VERSION:
5631     case OFP15_VERSION:
5632         ofputil_put_ofp13_table_stats(stats, reply);
5633         break;
5634
5635     default:
5636         OVS_NOT_REACHED();
5637     }
5638 }
5639
5640 static int
5641 ofputil_decode_ofp10_table_stats(struct ofpbuf *msg,
5642                                  struct ofputil_table_stats *stats,
5643                                  struct ofputil_table_features *features)
5644 {
5645     struct ofp10_table_stats *ots;
5646
5647     ots = ofpbuf_try_pull(msg, sizeof *ots);
5648     if (!ots) {
5649         return OFPERR_OFPBRC_BAD_LEN;
5650     }
5651
5652     features->table_id = ots->table_id;
5653     ovs_strlcpy(features->name, ots->name, sizeof features->name);
5654     features->max_entries = ntohl(ots->max_entries);
5655     features->match = features->wildcard = mf_bitmap_from_of10(ots->wildcards);
5656
5657     stats->table_id = ots->table_id;
5658     stats->active_count = ntohl(ots->active_count);
5659     stats->lookup_count = ntohll(get_32aligned_be64(&ots->lookup_count));
5660     stats->matched_count = ntohll(get_32aligned_be64(&ots->matched_count));
5661
5662     return 0;
5663 }
5664
5665 static int
5666 ofputil_decode_ofp11_table_stats(struct ofpbuf *msg,
5667                                  struct ofputil_table_stats *stats,
5668                                  struct ofputil_table_features *features)
5669 {
5670     struct ofp11_table_stats *ots;
5671
5672     ots = ofpbuf_try_pull(msg, sizeof *ots);
5673     if (!ots) {
5674         return OFPERR_OFPBRC_BAD_LEN;
5675     }
5676
5677     features->table_id = ots->table_id;
5678     ovs_strlcpy(features->name, ots->name, sizeof features->name);
5679     features->max_entries = ntohl(ots->max_entries);
5680     features->nonmiss.instructions = ovsinst_bitmap_from_openflow(
5681         ots->instructions, OFP11_VERSION);
5682     features->nonmiss.write.ofpacts = ofpact_bitmap_from_openflow(
5683         ots->write_actions, OFP11_VERSION);
5684     features->nonmiss.apply.ofpacts = ofpact_bitmap_from_openflow(
5685         ots->write_actions, OFP11_VERSION);
5686     features->miss = features->nonmiss;
5687     features->miss_config = ofputil_decode_table_miss(ots->config,
5688                                                       OFP11_VERSION);
5689     features->match = mf_bitmap_from_of11(ots->match);
5690     features->wildcard = mf_bitmap_from_of11(ots->wildcards);
5691     bitmap_or(features->match.bm, features->wildcard.bm, MFF_N_IDS);
5692
5693     stats->table_id = ots->table_id;
5694     stats->active_count = ntohl(ots->active_count);
5695     stats->lookup_count = ntohll(ots->lookup_count);
5696     stats->matched_count = ntohll(ots->matched_count);
5697
5698     return 0;
5699 }
5700
5701 static int
5702 ofputil_decode_ofp12_table_stats(struct ofpbuf *msg,
5703                                  struct ofputil_table_stats *stats,
5704                                  struct ofputil_table_features *features)
5705 {
5706     struct ofp12_table_stats *ots;
5707
5708     ots = ofpbuf_try_pull(msg, sizeof *ots);
5709     if (!ots) {
5710         return OFPERR_OFPBRC_BAD_LEN;
5711     }
5712
5713     features->table_id = ots->table_id;
5714     ovs_strlcpy(features->name, ots->name, sizeof features->name);
5715     features->metadata_match = ots->metadata_match;
5716     features->metadata_write = ots->metadata_write;
5717     features->miss_config = ofputil_decode_table_miss(ots->config,
5718                                                       OFP12_VERSION);
5719     features->max_entries = ntohl(ots->max_entries);
5720
5721     features->nonmiss.instructions = ovsinst_bitmap_from_openflow(
5722         ots->instructions, OFP12_VERSION);
5723     features->nonmiss.write.ofpacts = ofpact_bitmap_from_openflow(
5724         ots->write_actions, OFP12_VERSION);
5725     features->nonmiss.apply.ofpacts = ofpact_bitmap_from_openflow(
5726         ots->apply_actions, OFP12_VERSION);
5727     features->nonmiss.write.set_fields = oxm_bitmap_to_mf_bitmap(
5728         ots->write_setfields, OFP12_VERSION);
5729     features->nonmiss.apply.set_fields = oxm_bitmap_to_mf_bitmap(
5730         ots->apply_setfields, OFP12_VERSION);
5731     features->miss = features->nonmiss;
5732
5733     features->match = oxm_bitmap_to_mf_bitmap(ots->match, OFP12_VERSION);
5734     features->wildcard = oxm_bitmap_to_mf_bitmap(ots->wildcards,
5735                                                  OFP12_VERSION);
5736     bitmap_or(features->match.bm, features->wildcard.bm, MFF_N_IDS);
5737
5738     stats->table_id = ots->table_id;
5739     stats->active_count = ntohl(ots->active_count);
5740     stats->lookup_count = ntohll(ots->lookup_count);
5741     stats->matched_count = ntohll(ots->matched_count);
5742
5743     return 0;
5744 }
5745
5746 static int
5747 ofputil_decode_ofp13_table_stats(struct ofpbuf *msg,
5748                                  struct ofputil_table_stats *stats,
5749                                  struct ofputil_table_features *features)
5750 {
5751     struct ofp13_table_stats *ots;
5752
5753     ots = ofpbuf_try_pull(msg, sizeof *ots);
5754     if (!ots) {
5755         return OFPERR_OFPBRC_BAD_LEN;
5756     }
5757
5758     features->table_id = ots->table_id;
5759
5760     stats->table_id = ots->table_id;
5761     stats->active_count = ntohl(ots->active_count);
5762     stats->lookup_count = ntohll(ots->lookup_count);
5763     stats->matched_count = ntohll(ots->matched_count);
5764
5765     return 0;
5766 }
5767
5768 int
5769 ofputil_decode_table_stats_reply(struct ofpbuf *msg,
5770                                  struct ofputil_table_stats *stats,
5771                                  struct ofputil_table_features *features)
5772 {
5773     const struct ofp_header *oh;
5774
5775     if (!msg->header) {
5776         ofpraw_pull_assert(msg);
5777     }
5778     oh = msg->header;
5779
5780     if (!msg->size) {
5781         return EOF;
5782     }
5783
5784     memset(stats, 0, sizeof *stats);
5785     memset(features, 0, sizeof *features);
5786     features->supports_eviction = -1;
5787     features->supports_vacancy_events = -1;
5788
5789     switch ((enum ofp_version) oh->version) {
5790     case OFP10_VERSION:
5791         return ofputil_decode_ofp10_table_stats(msg, stats, features);
5792
5793     case OFP11_VERSION:
5794         return ofputil_decode_ofp11_table_stats(msg, stats, features);
5795
5796     case OFP12_VERSION:
5797         return ofputil_decode_ofp12_table_stats(msg, stats, features);
5798
5799     case OFP13_VERSION:
5800     case OFP14_VERSION:
5801     case OFP15_VERSION:
5802         return ofputil_decode_ofp13_table_stats(msg, stats, features);
5803
5804     default:
5805         OVS_NOT_REACHED();
5806     }
5807 }
5808 \f
5809 /* ofputil_flow_monitor_request */
5810
5811 /* Converts an NXST_FLOW_MONITOR request in 'msg' into an abstract
5812  * ofputil_flow_monitor_request in 'rq'.
5813  *
5814  * Multiple NXST_FLOW_MONITOR requests can be packed into a single OpenFlow
5815  * message.  Calling this function multiple times for a single 'msg' iterates
5816  * through the requests.  The caller must initially leave 'msg''s layer
5817  * pointers null and not modify them between calls.
5818  *
5819  * Returns 0 if successful, EOF if no requests were left in this 'msg',
5820  * otherwise an OFPERR_* value. */
5821 int
5822 ofputil_decode_flow_monitor_request(struct ofputil_flow_monitor_request *rq,
5823                                     struct ofpbuf *msg)
5824 {
5825     struct nx_flow_monitor_request *nfmr;
5826     uint16_t flags;
5827
5828     if (!msg->header) {
5829         ofpraw_pull_assert(msg);
5830     }
5831
5832     if (!msg->size) {
5833         return EOF;
5834     }
5835
5836     nfmr = ofpbuf_try_pull(msg, sizeof *nfmr);
5837     if (!nfmr) {
5838         VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR request has %"PRIu32" "
5839                      "leftover bytes at end", msg->size);
5840         return OFPERR_OFPBRC_BAD_LEN;
5841     }
5842
5843     flags = ntohs(nfmr->flags);
5844     if (!(flags & (NXFMF_ADD | NXFMF_DELETE | NXFMF_MODIFY))
5845         || flags & ~(NXFMF_INITIAL | NXFMF_ADD | NXFMF_DELETE
5846                      | NXFMF_MODIFY | NXFMF_ACTIONS | NXFMF_OWN)) {
5847         VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR has bad flags %#"PRIx16,
5848                      flags);
5849         return OFPERR_OFPMOFC_BAD_FLAGS;
5850     }
5851
5852     if (!is_all_zeros(nfmr->zeros, sizeof nfmr->zeros)) {
5853         return OFPERR_NXBRC_MUST_BE_ZERO;
5854     }
5855
5856     rq->id = ntohl(nfmr->id);
5857     rq->flags = flags;
5858     rq->out_port = u16_to_ofp(ntohs(nfmr->out_port));
5859     rq->table_id = nfmr->table_id;
5860
5861     return nx_pull_match(msg, ntohs(nfmr->match_len), &rq->match, NULL, NULL);
5862 }
5863
5864 void
5865 ofputil_append_flow_monitor_request(
5866     const struct ofputil_flow_monitor_request *rq, struct ofpbuf *msg)
5867 {
5868     struct nx_flow_monitor_request *nfmr;
5869     size_t start_ofs;
5870     int match_len;
5871
5872     if (!msg->size) {
5873         ofpraw_put(OFPRAW_NXST_FLOW_MONITOR_REQUEST, OFP10_VERSION, msg);
5874     }
5875
5876     start_ofs = msg->size;
5877     ofpbuf_put_zeros(msg, sizeof *nfmr);
5878     match_len = nx_put_match(msg, &rq->match, htonll(0), htonll(0));
5879
5880     nfmr = ofpbuf_at_assert(msg, start_ofs, sizeof *nfmr);
5881     nfmr->id = htonl(rq->id);
5882     nfmr->flags = htons(rq->flags);
5883     nfmr->out_port = htons(ofp_to_u16(rq->out_port));
5884     nfmr->match_len = htons(match_len);
5885     nfmr->table_id = rq->table_id;
5886 }
5887
5888 /* Converts an NXST_FLOW_MONITOR reply (also known as a flow update) in 'msg'
5889  * into an abstract ofputil_flow_update in 'update'.  The caller must have
5890  * initialized update->match to point to space allocated for a match.
5891  *
5892  * Uses 'ofpacts' to store the abstract OFPACT_* version of the update's
5893  * actions (except for NXFME_ABBREV, which never includes actions).  The caller
5894  * must initialize 'ofpacts' and retains ownership of it.  'update->ofpacts'
5895  * will point into the 'ofpacts' buffer.
5896  *
5897  * Multiple flow updates can be packed into a single OpenFlow message.  Calling
5898  * this function multiple times for a single 'msg' iterates through the
5899  * updates.  The caller must initially leave 'msg''s layer pointers null and
5900  * not modify them between calls.
5901  *
5902  * Returns 0 if successful, EOF if no updates were left in this 'msg',
5903  * otherwise an OFPERR_* value. */
5904 int
5905 ofputil_decode_flow_update(struct ofputil_flow_update *update,
5906                            struct ofpbuf *msg, struct ofpbuf *ofpacts)
5907 {
5908     struct nx_flow_update_header *nfuh;
5909     unsigned int length;
5910     struct ofp_header *oh;
5911
5912     if (!msg->header) {
5913         ofpraw_pull_assert(msg);
5914     }
5915
5916     if (!msg->size) {
5917         return EOF;
5918     }
5919
5920     if (msg->size < sizeof(struct nx_flow_update_header)) {
5921         goto bad_len;
5922     }
5923
5924     oh = msg->header;
5925
5926     nfuh = msg->data;
5927     update->event = ntohs(nfuh->event);
5928     length = ntohs(nfuh->length);
5929     if (length > msg->size || length % 8) {
5930         goto bad_len;
5931     }
5932
5933     if (update->event == NXFME_ABBREV) {
5934         struct nx_flow_update_abbrev *nfua;
5935
5936         if (length != sizeof *nfua) {
5937             goto bad_len;
5938         }
5939
5940         nfua = ofpbuf_pull(msg, sizeof *nfua);
5941         update->xid = nfua->xid;
5942         return 0;
5943     } else if (update->event == NXFME_ADDED
5944                || update->event == NXFME_DELETED
5945                || update->event == NXFME_MODIFIED) {
5946         struct nx_flow_update_full *nfuf;
5947         unsigned int actions_len;
5948         unsigned int match_len;
5949         enum ofperr error;
5950
5951         if (length < sizeof *nfuf) {
5952             goto bad_len;
5953         }
5954
5955         nfuf = ofpbuf_pull(msg, sizeof *nfuf);
5956         match_len = ntohs(nfuf->match_len);
5957         if (sizeof *nfuf + match_len > length) {
5958             goto bad_len;
5959         }
5960
5961         update->reason = ntohs(nfuf->reason);
5962         update->idle_timeout = ntohs(nfuf->idle_timeout);
5963         update->hard_timeout = ntohs(nfuf->hard_timeout);
5964         update->table_id = nfuf->table_id;
5965         update->cookie = nfuf->cookie;
5966         update->priority = ntohs(nfuf->priority);
5967
5968         error = nx_pull_match(msg, match_len, update->match, NULL, NULL);
5969         if (error) {
5970             return error;
5971         }
5972
5973         actions_len = length - sizeof *nfuf - ROUND_UP(match_len, 8);
5974         error = ofpacts_pull_openflow_actions(msg, actions_len, oh->version,
5975                                               ofpacts);
5976         if (error) {
5977             return error;
5978         }
5979
5980         update->ofpacts = ofpacts->data;
5981         update->ofpacts_len = ofpacts->size;
5982         return 0;
5983     } else {
5984         VLOG_WARN_RL(&bad_ofmsg_rl,
5985                      "NXST_FLOW_MONITOR reply has bad event %"PRIu16,
5986                      ntohs(nfuh->event));
5987         return OFPERR_NXBRC_FM_BAD_EVENT;
5988     }
5989
5990 bad_len:
5991     VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR reply has %"PRIu32" "
5992                  "leftover bytes at end", msg->size);
5993     return OFPERR_OFPBRC_BAD_LEN;
5994 }
5995
5996 uint32_t
5997 ofputil_decode_flow_monitor_cancel(const struct ofp_header *oh)
5998 {
5999     const struct nx_flow_monitor_cancel *cancel = ofpmsg_body(oh);
6000
6001     return ntohl(cancel->id);
6002 }
6003
6004 struct ofpbuf *
6005 ofputil_encode_flow_monitor_cancel(uint32_t id)
6006 {
6007     struct nx_flow_monitor_cancel *nfmc;
6008     struct ofpbuf *msg;
6009
6010     msg = ofpraw_alloc(OFPRAW_NXT_FLOW_MONITOR_CANCEL, OFP10_VERSION, 0);
6011     nfmc = ofpbuf_put_uninit(msg, sizeof *nfmc);
6012     nfmc->id = htonl(id);
6013     return msg;
6014 }
6015
6016 void
6017 ofputil_start_flow_update(struct ovs_list *replies)
6018 {
6019     struct ofpbuf *msg;
6020
6021     msg = ofpraw_alloc_xid(OFPRAW_NXST_FLOW_MONITOR_REPLY, OFP10_VERSION,
6022                            htonl(0), 1024);
6023
6024     list_init(replies);
6025     list_push_back(replies, &msg->list_node);
6026 }
6027
6028 void
6029 ofputil_append_flow_update(const struct ofputil_flow_update *update,
6030                            struct ovs_list *replies)
6031 {
6032     enum ofp_version version = ofpmp_version(replies);
6033     struct nx_flow_update_header *nfuh;
6034     struct ofpbuf *msg;
6035     size_t start_ofs;
6036
6037     msg = ofpbuf_from_list(list_back(replies));
6038     start_ofs = msg->size;
6039
6040     if (update->event == NXFME_ABBREV) {
6041         struct nx_flow_update_abbrev *nfua;
6042
6043         nfua = ofpbuf_put_zeros(msg, sizeof *nfua);
6044         nfua->xid = update->xid;
6045     } else {
6046         struct nx_flow_update_full *nfuf;
6047         int match_len;
6048
6049         ofpbuf_put_zeros(msg, sizeof *nfuf);
6050         match_len = nx_put_match(msg, update->match, htonll(0), htonll(0));
6051         ofpacts_put_openflow_actions(update->ofpacts, update->ofpacts_len, msg,
6052                                      version);
6053         nfuf = ofpbuf_at_assert(msg, start_ofs, sizeof *nfuf);
6054         nfuf->reason = htons(update->reason);
6055         nfuf->priority = htons(update->priority);
6056         nfuf->idle_timeout = htons(update->idle_timeout);
6057         nfuf->hard_timeout = htons(update->hard_timeout);
6058         nfuf->match_len = htons(match_len);
6059         nfuf->table_id = update->table_id;
6060         nfuf->cookie = update->cookie;
6061     }
6062
6063     nfuh = ofpbuf_at_assert(msg, start_ofs, sizeof *nfuh);
6064     nfuh->length = htons(msg->size - start_ofs);
6065     nfuh->event = htons(update->event);
6066
6067     ofpmp_postappend(replies, start_ofs);
6068 }
6069 \f
6070 struct ofpbuf *
6071 ofputil_encode_packet_out(const struct ofputil_packet_out *po,
6072                           enum ofputil_protocol protocol)
6073 {
6074     enum ofp_version ofp_version = ofputil_protocol_to_ofp_version(protocol);
6075     struct ofpbuf *msg;
6076     size_t size;
6077
6078     size = po->ofpacts_len;
6079     if (po->buffer_id == UINT32_MAX) {
6080         size += po->packet_len;
6081     }
6082
6083     switch (ofp_version) {
6084     case OFP10_VERSION: {
6085         struct ofp10_packet_out *opo;
6086         size_t actions_ofs;
6087
6088         msg = ofpraw_alloc(OFPRAW_OFPT10_PACKET_OUT, OFP10_VERSION, size);
6089         ofpbuf_put_zeros(msg, sizeof *opo);
6090         actions_ofs = msg->size;
6091         ofpacts_put_openflow_actions(po->ofpacts, po->ofpacts_len, msg,
6092                                      ofp_version);
6093
6094         opo = msg->msg;
6095         opo->buffer_id = htonl(po->buffer_id);
6096         opo->in_port = htons(ofp_to_u16(po->in_port));
6097         opo->actions_len = htons(msg->size - actions_ofs);
6098         break;
6099     }
6100
6101     case OFP11_VERSION:
6102     case OFP12_VERSION:
6103     case OFP13_VERSION:
6104     case OFP14_VERSION:
6105     case OFP15_VERSION: {
6106         struct ofp11_packet_out *opo;
6107         size_t len;
6108
6109         msg = ofpraw_alloc(OFPRAW_OFPT11_PACKET_OUT, ofp_version, size);
6110         ofpbuf_put_zeros(msg, sizeof *opo);
6111         len = ofpacts_put_openflow_actions(po->ofpacts, po->ofpacts_len, msg,
6112                                            ofp_version);
6113         opo = msg->msg;
6114         opo->buffer_id = htonl(po->buffer_id);
6115         opo->in_port = ofputil_port_to_ofp11(po->in_port);
6116         opo->actions_len = htons(len);
6117         break;
6118     }
6119
6120     default:
6121         OVS_NOT_REACHED();
6122     }
6123
6124     if (po->buffer_id == UINT32_MAX) {
6125         ofpbuf_put(msg, po->packet, po->packet_len);
6126     }
6127
6128     ofpmsg_update_length(msg);
6129
6130     return msg;
6131 }
6132 \f
6133 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
6134 struct ofpbuf *
6135 make_echo_request(enum ofp_version ofp_version)
6136 {
6137     return ofpraw_alloc_xid(OFPRAW_OFPT_ECHO_REQUEST, ofp_version,
6138                             htonl(0), 0);
6139 }
6140
6141 /* Creates and returns an OFPT_ECHO_REPLY message matching the
6142  * OFPT_ECHO_REQUEST message in 'rq'. */
6143 struct ofpbuf *
6144 make_echo_reply(const struct ofp_header *rq)
6145 {
6146     struct ofpbuf rq_buf;
6147     struct ofpbuf *reply;
6148
6149     ofpbuf_use_const(&rq_buf, rq, ntohs(rq->length));
6150     ofpraw_pull_assert(&rq_buf);
6151
6152     reply = ofpraw_alloc_reply(OFPRAW_OFPT_ECHO_REPLY, rq, rq_buf.size);
6153     ofpbuf_put(reply, rq_buf.data, rq_buf.size);
6154     return reply;
6155 }
6156
6157 struct ofpbuf *
6158 ofputil_encode_barrier_request(enum ofp_version ofp_version)
6159 {
6160     enum ofpraw type;
6161
6162     switch (ofp_version) {
6163     case OFP15_VERSION:
6164     case OFP14_VERSION:
6165     case OFP13_VERSION:
6166     case OFP12_VERSION:
6167     case OFP11_VERSION:
6168         type = OFPRAW_OFPT11_BARRIER_REQUEST;
6169         break;
6170
6171     case OFP10_VERSION:
6172         type = OFPRAW_OFPT10_BARRIER_REQUEST;
6173         break;
6174
6175     default:
6176         OVS_NOT_REACHED();
6177     }
6178
6179     return ofpraw_alloc(type, ofp_version, 0);
6180 }
6181
6182 const char *
6183 ofputil_frag_handling_to_string(enum ofp_config_flags flags)
6184 {
6185     switch (flags & OFPC_FRAG_MASK) {
6186     case OFPC_FRAG_NORMAL:   return "normal";
6187     case OFPC_FRAG_DROP:     return "drop";
6188     case OFPC_FRAG_REASM:    return "reassemble";
6189     case OFPC_FRAG_NX_MATCH: return "nx-match";
6190     }
6191
6192     OVS_NOT_REACHED();
6193 }
6194
6195 bool
6196 ofputil_frag_handling_from_string(const char *s, enum ofp_config_flags *flags)
6197 {
6198     if (!strcasecmp(s, "normal")) {
6199         *flags = OFPC_FRAG_NORMAL;
6200     } else if (!strcasecmp(s, "drop")) {
6201         *flags = OFPC_FRAG_DROP;
6202     } else if (!strcasecmp(s, "reassemble")) {
6203         *flags = OFPC_FRAG_REASM;
6204     } else if (!strcasecmp(s, "nx-match")) {
6205         *flags = OFPC_FRAG_NX_MATCH;
6206     } else {
6207         return false;
6208     }
6209     return true;
6210 }
6211
6212 /* Converts the OpenFlow 1.1+ port number 'ofp11_port' into an OpenFlow 1.0
6213  * port number and stores the latter in '*ofp10_port', for the purpose of
6214  * decoding OpenFlow 1.1+ protocol messages.  Returns 0 if successful,
6215  * otherwise an OFPERR_* number.  On error, stores OFPP_NONE in '*ofp10_port'.
6216  *
6217  * See the definition of OFP11_MAX for an explanation of the mapping. */
6218 enum ofperr
6219 ofputil_port_from_ofp11(ovs_be32 ofp11_port, ofp_port_t *ofp10_port)
6220 {
6221     uint32_t ofp11_port_h = ntohl(ofp11_port);
6222
6223     if (ofp11_port_h < ofp_to_u16(OFPP_MAX)) {
6224         *ofp10_port = u16_to_ofp(ofp11_port_h);
6225         return 0;
6226     } else if (ofp11_port_h >= ofp11_to_u32(OFPP11_MAX)) {
6227         *ofp10_port = u16_to_ofp(ofp11_port_h - OFPP11_OFFSET);
6228         return 0;
6229     } else {
6230         *ofp10_port = OFPP_NONE;
6231         VLOG_WARN_RL(&bad_ofmsg_rl, "port %"PRIu32" is outside the supported "
6232                      "range 0 through %d or 0x%"PRIx32" through 0x%"PRIx32,
6233                      ofp11_port_h, ofp_to_u16(OFPP_MAX) - 1,
6234                      ofp11_to_u32(OFPP11_MAX), UINT32_MAX);
6235         return OFPERR_OFPBAC_BAD_OUT_PORT;
6236     }
6237 }
6238
6239 /* Returns the OpenFlow 1.1+ port number equivalent to the OpenFlow 1.0 port
6240  * number 'ofp10_port', for encoding OpenFlow 1.1+ protocol messages.
6241  *
6242  * See the definition of OFP11_MAX for an explanation of the mapping. */
6243 ovs_be32
6244 ofputil_port_to_ofp11(ofp_port_t ofp10_port)
6245 {
6246     return htonl(ofp_to_u16(ofp10_port) < ofp_to_u16(OFPP_MAX)
6247                  ? ofp_to_u16(ofp10_port)
6248                  : ofp_to_u16(ofp10_port) + OFPP11_OFFSET);
6249 }
6250
6251 #define OFPUTIL_NAMED_PORTS                     \
6252         OFPUTIL_NAMED_PORT(IN_PORT)             \
6253         OFPUTIL_NAMED_PORT(TABLE)               \
6254         OFPUTIL_NAMED_PORT(NORMAL)              \
6255         OFPUTIL_NAMED_PORT(FLOOD)               \
6256         OFPUTIL_NAMED_PORT(ALL)                 \
6257         OFPUTIL_NAMED_PORT(CONTROLLER)          \
6258         OFPUTIL_NAMED_PORT(LOCAL)               \
6259         OFPUTIL_NAMED_PORT(ANY)                 \
6260         OFPUTIL_NAMED_PORT(UNSET)
6261
6262 /* For backwards compatibility, so that "none" is recognized as OFPP_ANY */
6263 #define OFPUTIL_NAMED_PORTS_WITH_NONE           \
6264         OFPUTIL_NAMED_PORTS                     \
6265         OFPUTIL_NAMED_PORT(NONE)
6266
6267 /* Stores the port number represented by 's' into '*portp'.  's' may be an
6268  * integer or, for reserved ports, the standard OpenFlow name for the port
6269  * (e.g. "LOCAL").
6270  *
6271  * Returns true if successful, false if 's' is not a valid OpenFlow port number
6272  * or name.  The caller should issue an error message in this case, because
6273  * this function usually does not.  (This gives the caller an opportunity to
6274  * look up the port name another way, e.g. by contacting the switch and listing
6275  * the names of all its ports).
6276  *
6277  * This function accepts OpenFlow 1.0 port numbers.  It also accepts a subset
6278  * of OpenFlow 1.1+ port numbers, mapping those port numbers into the 16-bit
6279  * range as described in include/openflow/openflow-1.1.h. */
6280 bool
6281 ofputil_port_from_string(const char *s, ofp_port_t *portp)
6282 {
6283     unsigned int port32; /* int is at least 32 bits wide. */
6284
6285     if (*s == '-') {
6286         VLOG_WARN("Negative value %s is not a valid port number.", s);
6287         return false;
6288     }
6289     *portp = 0;
6290     if (str_to_uint(s, 10, &port32)) {
6291         if (port32 < ofp_to_u16(OFPP_MAX)) {
6292             /* Pass. */
6293         } else if (port32 < ofp_to_u16(OFPP_FIRST_RESV)) {
6294             VLOG_WARN("port %u is a reserved OF1.0 port number that will "
6295                       "be translated to %u when talking to an OF1.1 or "
6296                       "later controller", port32, port32 + OFPP11_OFFSET);
6297         } else if (port32 <= ofp_to_u16(OFPP_LAST_RESV)) {
6298             char name[OFP_MAX_PORT_NAME_LEN];
6299
6300             ofputil_port_to_string(u16_to_ofp(port32), name, sizeof name);
6301             VLOG_WARN_ONCE("referring to port %s as %"PRIu32" is deprecated "
6302                            "for compatibility with OpenFlow 1.1 and later",
6303                            name, port32);
6304         } else if (port32 < ofp11_to_u32(OFPP11_MAX)) {
6305             VLOG_WARN("port %u is outside the supported range 0 through "
6306                       "%"PRIx16" or 0x%x through 0x%"PRIx32, port32,
6307                       UINT16_MAX, ofp11_to_u32(OFPP11_MAX), UINT32_MAX);
6308             return false;
6309         } else {
6310             port32 -= OFPP11_OFFSET;
6311         }
6312
6313         *portp = u16_to_ofp(port32);
6314         return true;
6315     } else {
6316         struct pair {
6317             const char *name;
6318             ofp_port_t value;
6319         };
6320         static const struct pair pairs[] = {
6321 #define OFPUTIL_NAMED_PORT(NAME) {#NAME, OFPP_##NAME},
6322             OFPUTIL_NAMED_PORTS_WITH_NONE
6323 #undef OFPUTIL_NAMED_PORT
6324         };
6325         const struct pair *p;
6326
6327         for (p = pairs; p < &pairs[ARRAY_SIZE(pairs)]; p++) {
6328             if (!strcasecmp(s, p->name)) {
6329                 *portp = p->value;
6330                 return true;
6331             }
6332         }
6333         return false;
6334     }
6335 }
6336
6337 /* Appends to 's' a string representation of the OpenFlow port number 'port'.
6338  * Most ports' string representation is just the port number, but for special
6339  * ports, e.g. OFPP_LOCAL, it is the name, e.g. "LOCAL". */
6340 void
6341 ofputil_format_port(ofp_port_t port, struct ds *s)
6342 {
6343     char name[OFP_MAX_PORT_NAME_LEN];
6344
6345     ofputil_port_to_string(port, name, sizeof name);
6346     ds_put_cstr(s, name);
6347 }
6348
6349 /* Puts in the 'bufsize' byte in 'namebuf' a null-terminated string
6350  * representation of OpenFlow port number 'port'.  Most ports are represented
6351  * as just the port number, but special ports, e.g. OFPP_LOCAL, are represented
6352  * by name, e.g. "LOCAL". */
6353 void
6354 ofputil_port_to_string(ofp_port_t port,
6355                        char namebuf[OFP_MAX_PORT_NAME_LEN], size_t bufsize)
6356 {
6357     switch (port) {
6358 #define OFPUTIL_NAMED_PORT(NAME)                        \
6359         case OFPP_##NAME:                               \
6360             ovs_strlcpy(namebuf, #NAME, bufsize);       \
6361             break;
6362         OFPUTIL_NAMED_PORTS
6363 #undef OFPUTIL_NAMED_PORT
6364
6365     default:
6366         snprintf(namebuf, bufsize, "%"PRIu16, port);
6367         break;
6368     }
6369 }
6370
6371 /* Stores the group id represented by 's' into '*group_idp'.  's' may be an
6372  * integer or, for reserved group IDs, the standard OpenFlow name for the group
6373  * (either "ANY" or "ALL").
6374  *
6375  * Returns true if successful, false if 's' is not a valid OpenFlow group ID or
6376  * name. */
6377 bool
6378 ofputil_group_from_string(const char *s, uint32_t *group_idp)
6379 {
6380     if (!strcasecmp(s, "any")) {
6381         *group_idp = OFPG11_ANY;
6382     } else if (!strcasecmp(s, "all")) {
6383         *group_idp = OFPG11_ALL;
6384     } else if (!str_to_uint(s, 10, group_idp)) {
6385         VLOG_WARN("%s is not a valid group ID.  (Valid group IDs are "
6386                   "32-bit nonnegative integers or the keywords ANY or "
6387                   "ALL.)", s);
6388         return false;
6389     }
6390
6391     return true;
6392 }
6393
6394 /* Appends to 's' a string representation of the OpenFlow group ID 'group_id'.
6395  * Most groups' string representation is just the number, but for special
6396  * groups, e.g. OFPG11_ALL, it is the name, e.g. "ALL". */
6397 void
6398 ofputil_format_group(uint32_t group_id, struct ds *s)
6399 {
6400     char name[MAX_GROUP_NAME_LEN];
6401
6402     ofputil_group_to_string(group_id, name, sizeof name);
6403     ds_put_cstr(s, name);
6404 }
6405
6406
6407 /* Puts in the 'bufsize' byte in 'namebuf' a null-terminated string
6408  * representation of OpenFlow group ID 'group_id'.  Most group are represented
6409  * as just their number, but special groups, e.g. OFPG11_ALL, are represented
6410  * by name, e.g. "ALL". */
6411 void
6412 ofputil_group_to_string(uint32_t group_id,
6413                         char namebuf[MAX_GROUP_NAME_LEN + 1], size_t bufsize)
6414 {
6415     switch (group_id) {
6416     case OFPG11_ALL:
6417         ovs_strlcpy(namebuf, "ALL", bufsize);
6418         break;
6419
6420     case OFPG11_ANY:
6421         ovs_strlcpy(namebuf, "ANY", bufsize);
6422         break;
6423
6424     default:
6425         snprintf(namebuf, bufsize, "%"PRIu32, group_id);
6426         break;
6427     }
6428 }
6429
6430 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
6431  * 'ofp_version', tries to pull the first element from the array.  If
6432  * successful, initializes '*pp' with an abstract representation of the
6433  * port and returns 0.  If no ports remain to be decoded, returns EOF.
6434  * On an error, returns a positive OFPERR_* value. */
6435 int
6436 ofputil_pull_phy_port(enum ofp_version ofp_version, struct ofpbuf *b,
6437                       struct ofputil_phy_port *pp)
6438 {
6439     memset(pp, 0, sizeof *pp);
6440
6441     switch (ofp_version) {
6442     case OFP10_VERSION: {
6443         const struct ofp10_phy_port *opp = ofpbuf_try_pull(b, sizeof *opp);
6444         return opp ? ofputil_decode_ofp10_phy_port(pp, opp) : EOF;
6445     }
6446     case OFP11_VERSION:
6447     case OFP12_VERSION:
6448     case OFP13_VERSION: {
6449         const struct ofp11_port *op = ofpbuf_try_pull(b, sizeof *op);
6450         return op ? ofputil_decode_ofp11_port(pp, op) : EOF;
6451     }
6452     case OFP14_VERSION:
6453     case OFP15_VERSION:
6454         return b->size ? ofputil_pull_ofp14_port(pp, b) : EOF;
6455     default:
6456         OVS_NOT_REACHED();
6457     }
6458 }
6459
6460 static void
6461 ofputil_normalize_match__(struct match *match, bool may_log)
6462 {
6463     enum {
6464         MAY_NW_ADDR     = 1 << 0, /* nw_src, nw_dst */
6465         MAY_TP_ADDR     = 1 << 1, /* tp_src, tp_dst */
6466         MAY_NW_PROTO    = 1 << 2, /* nw_proto */
6467         MAY_IPVx        = 1 << 3, /* tos, frag, ttl */
6468         MAY_ARP_SHA     = 1 << 4, /* arp_sha */
6469         MAY_ARP_THA     = 1 << 5, /* arp_tha */
6470         MAY_IPV6        = 1 << 6, /* ipv6_src, ipv6_dst, ipv6_label */
6471         MAY_ND_TARGET   = 1 << 7, /* nd_target */
6472         MAY_MPLS        = 1 << 8, /* mpls label and tc */
6473     } may_match;
6474
6475     struct flow_wildcards wc;
6476
6477     /* Figure out what fields may be matched. */
6478     if (match->flow.dl_type == htons(ETH_TYPE_IP)) {
6479         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_NW_ADDR;
6480         if (match->flow.nw_proto == IPPROTO_TCP ||
6481             match->flow.nw_proto == IPPROTO_UDP ||
6482             match->flow.nw_proto == IPPROTO_SCTP ||
6483             match->flow.nw_proto == IPPROTO_ICMP) {
6484             may_match |= MAY_TP_ADDR;
6485         }
6486     } else if (match->flow.dl_type == htons(ETH_TYPE_IPV6)) {
6487         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_IPV6;
6488         if (match->flow.nw_proto == IPPROTO_TCP ||
6489             match->flow.nw_proto == IPPROTO_UDP ||
6490             match->flow.nw_proto == IPPROTO_SCTP) {
6491             may_match |= MAY_TP_ADDR;
6492         } else if (match->flow.nw_proto == IPPROTO_ICMPV6) {
6493             may_match |= MAY_TP_ADDR;
6494             if (match->flow.tp_src == htons(ND_NEIGHBOR_SOLICIT)) {
6495                 may_match |= MAY_ND_TARGET | MAY_ARP_SHA;
6496             } else if (match->flow.tp_src == htons(ND_NEIGHBOR_ADVERT)) {
6497                 may_match |= MAY_ND_TARGET | MAY_ARP_THA;
6498             }
6499         }
6500     } else if (match->flow.dl_type == htons(ETH_TYPE_ARP) ||
6501                match->flow.dl_type == htons(ETH_TYPE_RARP)) {
6502         may_match = MAY_NW_PROTO | MAY_NW_ADDR | MAY_ARP_SHA | MAY_ARP_THA;
6503     } else if (eth_type_mpls(match->flow.dl_type)) {
6504         may_match = MAY_MPLS;
6505     } else {
6506         may_match = 0;
6507     }
6508
6509     /* Clear the fields that may not be matched. */
6510     wc = match->wc;
6511     if (!(may_match & MAY_NW_ADDR)) {
6512         wc.masks.nw_src = wc.masks.nw_dst = htonl(0);
6513     }
6514     if (!(may_match & MAY_TP_ADDR)) {
6515         wc.masks.tp_src = wc.masks.tp_dst = htons(0);
6516     }
6517     if (!(may_match & MAY_NW_PROTO)) {
6518         wc.masks.nw_proto = 0;
6519     }
6520     if (!(may_match & MAY_IPVx)) {
6521         wc.masks.nw_tos = 0;
6522         wc.masks.nw_ttl = 0;
6523     }
6524     if (!(may_match & MAY_ARP_SHA)) {
6525         memset(wc.masks.arp_sha, 0, ETH_ADDR_LEN);
6526     }
6527     if (!(may_match & MAY_ARP_THA)) {
6528         memset(wc.masks.arp_tha, 0, ETH_ADDR_LEN);
6529     }
6530     if (!(may_match & MAY_IPV6)) {
6531         wc.masks.ipv6_src = wc.masks.ipv6_dst = in6addr_any;
6532         wc.masks.ipv6_label = htonl(0);
6533     }
6534     if (!(may_match & MAY_ND_TARGET)) {
6535         wc.masks.nd_target = in6addr_any;
6536     }
6537     if (!(may_match & MAY_MPLS)) {
6538         memset(wc.masks.mpls_lse, 0, sizeof wc.masks.mpls_lse);
6539     }
6540
6541     /* Log any changes. */
6542     if (!flow_wildcards_equal(&wc, &match->wc)) {
6543         bool log = may_log && !VLOG_DROP_INFO(&bad_ofmsg_rl);
6544         char *pre = log ? match_to_string(match, OFP_DEFAULT_PRIORITY) : NULL;
6545
6546         match->wc = wc;
6547         match_zero_wildcarded_fields(match);
6548
6549         if (log) {
6550             char *post = match_to_string(match, OFP_DEFAULT_PRIORITY);
6551             VLOG_INFO("normalization changed ofp_match, details:");
6552             VLOG_INFO(" pre: %s", pre);
6553             VLOG_INFO("post: %s", post);
6554             free(pre);
6555             free(post);
6556         }
6557     }
6558 }
6559
6560 /* "Normalizes" the wildcards in 'match'.  That means:
6561  *
6562  *    1. If the type of level N is known, then only the valid fields for that
6563  *       level may be specified.  For example, ARP does not have a TOS field,
6564  *       so nw_tos must be wildcarded if 'match' specifies an ARP flow.
6565  *       Similarly, IPv4 does not have any IPv6 addresses, so ipv6_src and
6566  *       ipv6_dst (and other fields) must be wildcarded if 'match' specifies an
6567  *       IPv4 flow.
6568  *
6569  *    2. If the type of level N is not known (or not understood by Open
6570  *       vSwitch), then no fields at all for that level may be specified.  For
6571  *       example, Open vSwitch does not understand SCTP, an L4 protocol, so the
6572  *       L4 fields tp_src and tp_dst must be wildcarded if 'match' specifies an
6573  *       SCTP flow.
6574  *
6575  * If this function changes 'match', it logs a rate-limited informational
6576  * message. */
6577 void
6578 ofputil_normalize_match(struct match *match)
6579 {
6580     ofputil_normalize_match__(match, true);
6581 }
6582
6583 /* Same as ofputil_normalize_match() without the logging.  Thus, this function
6584  * is suitable for a program's internal use, whereas ofputil_normalize_match()
6585  * sense for use on flows received from elsewhere (so that a bug in the program
6586  * that sent them can be reported and corrected). */
6587 void
6588 ofputil_normalize_match_quiet(struct match *match)
6589 {
6590     ofputil_normalize_match__(match, false);
6591 }
6592
6593 /* Parses a key or a key-value pair from '*stringp'.
6594  *
6595  * On success: Stores the key into '*keyp'.  Stores the value, if present, into
6596  * '*valuep', otherwise an empty string.  Advances '*stringp' past the end of
6597  * the key-value pair, preparing it for another call.  '*keyp' and '*valuep'
6598  * are substrings of '*stringp' created by replacing some of its bytes by null
6599  * terminators.  Returns true.
6600  *
6601  * If '*stringp' is just white space or commas, sets '*keyp' and '*valuep' to
6602  * NULL and returns false. */
6603 bool
6604 ofputil_parse_key_value(char **stringp, char **keyp, char **valuep)
6605 {
6606     char *pos, *key, *value;
6607     size_t key_len;
6608
6609     pos = *stringp;
6610     pos += strspn(pos, ", \t\r\n");
6611     if (*pos == '\0') {
6612         *keyp = *valuep = NULL;
6613         return false;
6614     }
6615
6616     key = pos;
6617     key_len = strcspn(pos, ":=(, \t\r\n");
6618     if (key[key_len] == ':' || key[key_len] == '=') {
6619         /* The value can be separated by a colon. */
6620         size_t value_len;
6621
6622         value = key + key_len + 1;
6623         value_len = strcspn(value, ", \t\r\n");
6624         pos = value + value_len + (value[value_len] != '\0');
6625         value[value_len] = '\0';
6626     } else if (key[key_len] == '(') {
6627         /* The value can be surrounded by balanced parentheses.  The outermost
6628          * set of parentheses is removed. */
6629         int level = 1;
6630         size_t value_len;
6631
6632         value = key + key_len + 1;
6633         for (value_len = 0; level > 0; value_len++) {
6634             switch (value[value_len]) {
6635             case '\0':
6636                 level = 0;
6637                 break;
6638
6639             case '(':
6640                 level++;
6641                 break;
6642
6643             case ')':
6644                 level--;
6645                 break;
6646             }
6647         }
6648         value[value_len - 1] = '\0';
6649         pos = value + value_len;
6650     } else {
6651         /* There might be no value at all. */
6652         value = key + key_len;  /* Will become the empty string below. */
6653         pos = key + key_len + (key[key_len] != '\0');
6654     }
6655     key[key_len] = '\0';
6656
6657     *stringp = pos;
6658     *keyp = key;
6659     *valuep = value;
6660     return true;
6661 }
6662
6663 /* Encode a dump ports request for 'port', the encoded message
6664  * will be for OpenFlow version 'ofp_version'. Returns message
6665  * as a struct ofpbuf. Returns encoded message on success, NULL on error */
6666 struct ofpbuf *
6667 ofputil_encode_dump_ports_request(enum ofp_version ofp_version, ofp_port_t port)
6668 {
6669     struct ofpbuf *request;
6670
6671     switch (ofp_version) {
6672     case OFP10_VERSION: {
6673         struct ofp10_port_stats_request *req;
6674         request = ofpraw_alloc(OFPRAW_OFPST10_PORT_REQUEST, ofp_version, 0);
6675         req = ofpbuf_put_zeros(request, sizeof *req);
6676         req->port_no = htons(ofp_to_u16(port));
6677         break;
6678     }
6679     case OFP11_VERSION:
6680     case OFP12_VERSION:
6681     case OFP13_VERSION:
6682     case OFP14_VERSION:
6683     case OFP15_VERSION: {
6684         struct ofp11_port_stats_request *req;
6685         request = ofpraw_alloc(OFPRAW_OFPST11_PORT_REQUEST, ofp_version, 0);
6686         req = ofpbuf_put_zeros(request, sizeof *req);
6687         req->port_no = ofputil_port_to_ofp11(port);
6688         break;
6689     }
6690     default:
6691         OVS_NOT_REACHED();
6692     }
6693
6694     return request;
6695 }
6696
6697 static void
6698 ofputil_port_stats_to_ofp10(const struct ofputil_port_stats *ops,
6699                             struct ofp10_port_stats *ps10)
6700 {
6701     ps10->port_no = htons(ofp_to_u16(ops->port_no));
6702     memset(ps10->pad, 0, sizeof ps10->pad);
6703     put_32aligned_be64(&ps10->rx_packets, htonll(ops->stats.rx_packets));
6704     put_32aligned_be64(&ps10->tx_packets, htonll(ops->stats.tx_packets));
6705     put_32aligned_be64(&ps10->rx_bytes, htonll(ops->stats.rx_bytes));
6706     put_32aligned_be64(&ps10->tx_bytes, htonll(ops->stats.tx_bytes));
6707     put_32aligned_be64(&ps10->rx_dropped, htonll(ops->stats.rx_dropped));
6708     put_32aligned_be64(&ps10->tx_dropped, htonll(ops->stats.tx_dropped));
6709     put_32aligned_be64(&ps10->rx_errors, htonll(ops->stats.rx_errors));
6710     put_32aligned_be64(&ps10->tx_errors, htonll(ops->stats.tx_errors));
6711     put_32aligned_be64(&ps10->rx_frame_err, htonll(ops->stats.rx_frame_errors));
6712     put_32aligned_be64(&ps10->rx_over_err, htonll(ops->stats.rx_over_errors));
6713     put_32aligned_be64(&ps10->rx_crc_err, htonll(ops->stats.rx_crc_errors));
6714     put_32aligned_be64(&ps10->collisions, htonll(ops->stats.collisions));
6715 }
6716
6717 static void
6718 ofputil_port_stats_to_ofp11(const struct ofputil_port_stats *ops,
6719                             struct ofp11_port_stats *ps11)
6720 {
6721     ps11->port_no = ofputil_port_to_ofp11(ops->port_no);
6722     memset(ps11->pad, 0, sizeof ps11->pad);
6723     ps11->rx_packets = htonll(ops->stats.rx_packets);
6724     ps11->tx_packets = htonll(ops->stats.tx_packets);
6725     ps11->rx_bytes = htonll(ops->stats.rx_bytes);
6726     ps11->tx_bytes = htonll(ops->stats.tx_bytes);
6727     ps11->rx_dropped = htonll(ops->stats.rx_dropped);
6728     ps11->tx_dropped = htonll(ops->stats.tx_dropped);
6729     ps11->rx_errors = htonll(ops->stats.rx_errors);
6730     ps11->tx_errors = htonll(ops->stats.tx_errors);
6731     ps11->rx_frame_err = htonll(ops->stats.rx_frame_errors);
6732     ps11->rx_over_err = htonll(ops->stats.rx_over_errors);
6733     ps11->rx_crc_err = htonll(ops->stats.rx_crc_errors);
6734     ps11->collisions = htonll(ops->stats.collisions);
6735 }
6736
6737 static void
6738 ofputil_port_stats_to_ofp13(const struct ofputil_port_stats *ops,
6739                             struct ofp13_port_stats *ps13)
6740 {
6741     ofputil_port_stats_to_ofp11(ops, &ps13->ps);
6742     ps13->duration_sec = htonl(ops->duration_sec);
6743     ps13->duration_nsec = htonl(ops->duration_nsec);
6744 }
6745
6746 static void
6747 ofputil_append_ofp14_port_stats(const struct ofputil_port_stats *ops,
6748                                 struct ovs_list *replies)
6749 {
6750     struct ofp14_port_stats_prop_ethernet *eth;
6751     struct ofp14_port_stats *ps14;
6752     struct ofpbuf *reply;
6753
6754     reply = ofpmp_reserve(replies, sizeof *ps14 + sizeof *eth);
6755
6756     ps14 = ofpbuf_put_uninit(reply, sizeof *ps14);
6757     ps14->length = htons(sizeof *ps14 + sizeof *eth);
6758     memset(ps14->pad, 0, sizeof ps14->pad);
6759     ps14->port_no = ofputil_port_to_ofp11(ops->port_no);
6760     ps14->duration_sec = htonl(ops->duration_sec);
6761     ps14->duration_nsec = htonl(ops->duration_nsec);
6762     ps14->rx_packets = htonll(ops->stats.rx_packets);
6763     ps14->tx_packets = htonll(ops->stats.tx_packets);
6764     ps14->rx_bytes = htonll(ops->stats.rx_bytes);
6765     ps14->tx_bytes = htonll(ops->stats.tx_bytes);
6766     ps14->rx_dropped = htonll(ops->stats.rx_dropped);
6767     ps14->tx_dropped = htonll(ops->stats.tx_dropped);
6768     ps14->rx_errors = htonll(ops->stats.rx_errors);
6769     ps14->tx_errors = htonll(ops->stats.tx_errors);
6770
6771     eth = ofpbuf_put_uninit(reply, sizeof *eth);
6772     eth->type = htons(OFPPSPT14_ETHERNET);
6773     eth->length = htons(sizeof *eth);
6774     memset(eth->pad, 0, sizeof eth->pad);
6775     eth->rx_frame_err = htonll(ops->stats.rx_frame_errors);
6776     eth->rx_over_err = htonll(ops->stats.rx_over_errors);
6777     eth->rx_crc_err = htonll(ops->stats.rx_crc_errors);
6778     eth->collisions = htonll(ops->stats.collisions);
6779 }
6780
6781 /* Encode a ports stat for 'ops' and append it to 'replies'. */
6782 void
6783 ofputil_append_port_stat(struct ovs_list *replies,
6784                          const struct ofputil_port_stats *ops)
6785 {
6786     switch (ofpmp_version(replies)) {
6787     case OFP13_VERSION: {
6788         struct ofp13_port_stats *reply = ofpmp_append(replies, sizeof *reply);
6789         ofputil_port_stats_to_ofp13(ops, reply);
6790         break;
6791     }
6792     case OFP12_VERSION:
6793     case OFP11_VERSION: {
6794         struct ofp11_port_stats *reply = ofpmp_append(replies, sizeof *reply);
6795         ofputil_port_stats_to_ofp11(ops, reply);
6796         break;
6797     }
6798
6799     case OFP10_VERSION: {
6800         struct ofp10_port_stats *reply = ofpmp_append(replies, sizeof *reply);
6801         ofputil_port_stats_to_ofp10(ops, reply);
6802         break;
6803     }
6804
6805     case OFP14_VERSION:
6806     case OFP15_VERSION:
6807         ofputil_append_ofp14_port_stats(ops, replies);
6808         break;
6809
6810     default:
6811         OVS_NOT_REACHED();
6812     }
6813 }
6814
6815 static enum ofperr
6816 ofputil_port_stats_from_ofp10(struct ofputil_port_stats *ops,
6817                               const struct ofp10_port_stats *ps10)
6818 {
6819     memset(ops, 0, sizeof *ops);
6820
6821     ops->port_no = u16_to_ofp(ntohs(ps10->port_no));
6822     ops->stats.rx_packets = ntohll(get_32aligned_be64(&ps10->rx_packets));
6823     ops->stats.tx_packets = ntohll(get_32aligned_be64(&ps10->tx_packets));
6824     ops->stats.rx_bytes = ntohll(get_32aligned_be64(&ps10->rx_bytes));
6825     ops->stats.tx_bytes = ntohll(get_32aligned_be64(&ps10->tx_bytes));
6826     ops->stats.rx_dropped = ntohll(get_32aligned_be64(&ps10->rx_dropped));
6827     ops->stats.tx_dropped = ntohll(get_32aligned_be64(&ps10->tx_dropped));
6828     ops->stats.rx_errors = ntohll(get_32aligned_be64(&ps10->rx_errors));
6829     ops->stats.tx_errors = ntohll(get_32aligned_be64(&ps10->tx_errors));
6830     ops->stats.rx_frame_errors =
6831         ntohll(get_32aligned_be64(&ps10->rx_frame_err));
6832     ops->stats.rx_over_errors = ntohll(get_32aligned_be64(&ps10->rx_over_err));
6833     ops->stats.rx_crc_errors = ntohll(get_32aligned_be64(&ps10->rx_crc_err));
6834     ops->stats.collisions = ntohll(get_32aligned_be64(&ps10->collisions));
6835     ops->duration_sec = ops->duration_nsec = UINT32_MAX;
6836
6837     return 0;
6838 }
6839
6840 static enum ofperr
6841 ofputil_port_stats_from_ofp11(struct ofputil_port_stats *ops,
6842                               const struct ofp11_port_stats *ps11)
6843 {
6844     enum ofperr error;
6845
6846     memset(ops, 0, sizeof *ops);
6847     error = ofputil_port_from_ofp11(ps11->port_no, &ops->port_no);
6848     if (error) {
6849         return error;
6850     }
6851
6852     ops->stats.rx_packets = ntohll(ps11->rx_packets);
6853     ops->stats.tx_packets = ntohll(ps11->tx_packets);
6854     ops->stats.rx_bytes = ntohll(ps11->rx_bytes);
6855     ops->stats.tx_bytes = ntohll(ps11->tx_bytes);
6856     ops->stats.rx_dropped = ntohll(ps11->rx_dropped);
6857     ops->stats.tx_dropped = ntohll(ps11->tx_dropped);
6858     ops->stats.rx_errors = ntohll(ps11->rx_errors);
6859     ops->stats.tx_errors = ntohll(ps11->tx_errors);
6860     ops->stats.rx_frame_errors = ntohll(ps11->rx_frame_err);
6861     ops->stats.rx_over_errors = ntohll(ps11->rx_over_err);
6862     ops->stats.rx_crc_errors = ntohll(ps11->rx_crc_err);
6863     ops->stats.collisions = ntohll(ps11->collisions);
6864     ops->duration_sec = ops->duration_nsec = UINT32_MAX;
6865
6866     return 0;
6867 }
6868
6869 static enum ofperr
6870 ofputil_port_stats_from_ofp13(struct ofputil_port_stats *ops,
6871                               const struct ofp13_port_stats *ps13)
6872 {
6873     enum ofperr error = ofputil_port_stats_from_ofp11(ops, &ps13->ps);
6874     if (!error) {
6875         ops->duration_sec = ntohl(ps13->duration_sec);
6876         ops->duration_nsec = ntohl(ps13->duration_nsec);
6877     }
6878     return error;
6879 }
6880
6881 static enum ofperr
6882 parse_ofp14_port_stats_ethernet_property(const struct ofpbuf *payload,
6883                                          struct ofputil_port_stats *ops)
6884 {
6885     const struct ofp14_port_stats_prop_ethernet *eth = payload->data;
6886
6887     if (payload->size != sizeof *eth) {
6888         return OFPERR_OFPBPC_BAD_LEN;
6889     }
6890
6891     ops->stats.rx_frame_errors = ntohll(eth->rx_frame_err);
6892     ops->stats.rx_over_errors = ntohll(eth->rx_over_err);
6893     ops->stats.rx_crc_errors = ntohll(eth->rx_crc_err);
6894     ops->stats.collisions = ntohll(eth->collisions);
6895
6896     return 0;
6897 }
6898
6899 static enum ofperr
6900 ofputil_pull_ofp14_port_stats(struct ofputil_port_stats *ops,
6901                               struct ofpbuf *msg)
6902 {
6903     const struct ofp14_port_stats *ps14;
6904     struct ofpbuf properties;
6905     enum ofperr error;
6906     size_t len;
6907
6908     ps14 = ofpbuf_try_pull(msg, sizeof *ps14);
6909     if (!ps14) {
6910         return OFPERR_OFPBRC_BAD_LEN;
6911     }
6912
6913     len = ntohs(ps14->length);
6914     if (len < sizeof *ps14 || len - sizeof *ps14 > msg->size) {
6915         return OFPERR_OFPBRC_BAD_LEN;
6916     }
6917     len -= sizeof *ps14;
6918     ofpbuf_use_const(&properties, ofpbuf_pull(msg, len), len);
6919
6920     error = ofputil_port_from_ofp11(ps14->port_no, &ops->port_no);
6921     if (error) {
6922         return error;
6923     }
6924
6925     ops->duration_sec = ntohl(ps14->duration_sec);
6926     ops->duration_nsec = ntohl(ps14->duration_nsec);
6927     ops->stats.rx_packets = ntohll(ps14->rx_packets);
6928     ops->stats.tx_packets = ntohll(ps14->tx_packets);
6929     ops->stats.rx_bytes = ntohll(ps14->rx_bytes);
6930     ops->stats.tx_bytes = ntohll(ps14->tx_bytes);
6931     ops->stats.rx_dropped = ntohll(ps14->rx_dropped);
6932     ops->stats.tx_dropped = ntohll(ps14->tx_dropped);
6933     ops->stats.rx_errors = ntohll(ps14->rx_errors);
6934     ops->stats.tx_errors = ntohll(ps14->tx_errors);
6935     ops->stats.rx_frame_errors = UINT64_MAX;
6936     ops->stats.rx_over_errors = UINT64_MAX;
6937     ops->stats.rx_crc_errors = UINT64_MAX;
6938     ops->stats.collisions = UINT64_MAX;
6939
6940     while (properties.size > 0) {
6941         struct ofpbuf payload;
6942         enum ofperr error;
6943         uint16_t type;
6944
6945         error = ofputil_pull_property(&properties, &payload, &type);
6946         if (error) {
6947             return error;
6948         }
6949
6950         switch (type) {
6951         case OFPPSPT14_ETHERNET:
6952             error = parse_ofp14_port_stats_ethernet_property(&payload, ops);
6953             break;
6954
6955         default:
6956             log_property(true, "unknown port stats property %"PRIu16, type);
6957             error = 0;
6958             break;
6959         }
6960
6961         if (error) {
6962             return error;
6963         }
6964     }
6965
6966     return 0;
6967 }
6968
6969 /* Returns the number of port stats elements in OFPTYPE_PORT_STATS_REPLY
6970  * message 'oh'. */
6971 size_t
6972 ofputil_count_port_stats(const struct ofp_header *oh)
6973 {
6974     struct ofputil_port_stats ps;
6975     struct ofpbuf b;
6976     size_t n = 0;
6977
6978     ofpbuf_use_const(&b, oh, ntohs(oh->length));
6979     ofpraw_pull_assert(&b);
6980     while (!ofputil_decode_port_stats(&ps, &b)) {
6981         n++;
6982     }
6983     return n;
6984 }
6985
6986 /* Converts an OFPST_PORT_STATS reply in 'msg' into an abstract
6987  * ofputil_port_stats in 'ps'.
6988  *
6989  * Multiple OFPST_PORT_STATS replies can be packed into a single OpenFlow
6990  * message.  Calling this function multiple times for a single 'msg' iterates
6991  * through the replies.  The caller must initially leave 'msg''s layer pointers
6992  * null and not modify them between calls.
6993  *
6994  * Returns 0 if successful, EOF if no replies were left in this 'msg',
6995  * otherwise a positive errno value. */
6996 int
6997 ofputil_decode_port_stats(struct ofputil_port_stats *ps, struct ofpbuf *msg)
6998 {
6999     enum ofperr error;
7000     enum ofpraw raw;
7001
7002     error = (msg->header ? ofpraw_decode(&raw, msg->header)
7003              : ofpraw_pull(&raw, msg));
7004     if (error) {
7005         return error;
7006     }
7007
7008     if (!msg->size) {
7009         return EOF;
7010     } else if (raw == OFPRAW_OFPST14_PORT_REPLY) {
7011         return ofputil_pull_ofp14_port_stats(ps, msg);
7012     } else if (raw == OFPRAW_OFPST13_PORT_REPLY) {
7013         const struct ofp13_port_stats *ps13;
7014
7015         ps13 = ofpbuf_try_pull(msg, sizeof *ps13);
7016         if (!ps13) {
7017             goto bad_len;
7018         }
7019         return ofputil_port_stats_from_ofp13(ps, ps13);
7020     } else if (raw == OFPRAW_OFPST11_PORT_REPLY) {
7021         const struct ofp11_port_stats *ps11;
7022
7023         ps11 = ofpbuf_try_pull(msg, sizeof *ps11);
7024         if (!ps11) {
7025             goto bad_len;
7026         }
7027         return ofputil_port_stats_from_ofp11(ps, ps11);
7028     } else if (raw == OFPRAW_OFPST10_PORT_REPLY) {
7029         const struct ofp10_port_stats *ps10;
7030
7031         ps10 = ofpbuf_try_pull(msg, sizeof *ps10);
7032         if (!ps10) {
7033             goto bad_len;
7034         }
7035         return ofputil_port_stats_from_ofp10(ps, ps10);
7036     } else {
7037         OVS_NOT_REACHED();
7038     }
7039
7040  bad_len:
7041     VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_PORT reply has %"PRIu32" leftover "
7042                  "bytes at end", msg->size);
7043     return OFPERR_OFPBRC_BAD_LEN;
7044 }
7045
7046 /* Parse a port status request message into a 16 bit OpenFlow 1.0
7047  * port number and stores the latter in '*ofp10_port'.
7048  * Returns 0 if successful, otherwise an OFPERR_* number. */
7049 enum ofperr
7050 ofputil_decode_port_stats_request(const struct ofp_header *request,
7051                                   ofp_port_t *ofp10_port)
7052 {
7053     switch ((enum ofp_version)request->version) {
7054     case OFP15_VERSION:
7055     case OFP14_VERSION:
7056     case OFP13_VERSION:
7057     case OFP12_VERSION:
7058     case OFP11_VERSION: {
7059         const struct ofp11_port_stats_request *psr11 = ofpmsg_body(request);
7060         return ofputil_port_from_ofp11(psr11->port_no, ofp10_port);
7061     }
7062
7063     case OFP10_VERSION: {
7064         const struct ofp10_port_stats_request *psr10 = ofpmsg_body(request);
7065         *ofp10_port = u16_to_ofp(ntohs(psr10->port_no));
7066         return 0;
7067     }
7068
7069     default:
7070         OVS_NOT_REACHED();
7071     }
7072 }
7073
7074 /* Frees all of the "struct ofputil_bucket"s in the 'buckets' list. */
7075 void
7076 ofputil_bucket_list_destroy(struct ovs_list *buckets)
7077 {
7078     struct ofputil_bucket *bucket;
7079
7080     LIST_FOR_EACH_POP (bucket, list_node, buckets) {
7081         free(bucket->ofpacts);
7082         free(bucket);
7083     }
7084 }
7085
7086 /* Clones 'bucket' and its ofpacts data */
7087 static struct ofputil_bucket *
7088 ofputil_bucket_clone_data(const struct ofputil_bucket *bucket)
7089 {
7090     struct ofputil_bucket *new;
7091
7092     new = xmemdup(bucket, sizeof *bucket);
7093     new->ofpacts = xmemdup(bucket->ofpacts, bucket->ofpacts_len);
7094
7095     return new;
7096 }
7097
7098 /* Clones each of the buckets in the list 'src' appending them
7099  * in turn to 'dest' which should be an initialised list.
7100  * An exception is that if the pointer value of a bucket in 'src'
7101  * matches 'skip' then it is not cloned or appended to 'dest'.
7102  * This allows all of 'src' or 'all of 'src' except 'skip' to
7103  * be cloned and appended to 'dest'. */
7104 void
7105 ofputil_bucket_clone_list(struct ovs_list *dest, const struct ovs_list *src,
7106                           const struct ofputil_bucket *skip)
7107 {
7108     struct ofputil_bucket *bucket;
7109
7110     LIST_FOR_EACH (bucket, list_node, src) {
7111         struct ofputil_bucket *new_bucket;
7112
7113         if (bucket == skip) {
7114             continue;
7115         }
7116
7117         new_bucket = ofputil_bucket_clone_data(bucket);
7118         list_push_back(dest, &new_bucket->list_node);
7119     }
7120 }
7121
7122 /* Find a bucket in the list 'buckets' whose bucket id is 'bucket_id'
7123  * Returns the first bucket found or NULL if no buckets are found. */
7124 struct ofputil_bucket *
7125 ofputil_bucket_find(const struct ovs_list *buckets, uint32_t bucket_id)
7126 {
7127     struct ofputil_bucket *bucket;
7128
7129     if (bucket_id > OFPG15_BUCKET_MAX) {
7130         return NULL;
7131     }
7132
7133     LIST_FOR_EACH (bucket, list_node, buckets) {
7134         if (bucket->bucket_id == bucket_id) {
7135             return bucket;
7136         }
7137     }
7138
7139     return NULL;
7140 }
7141
7142 /* Returns true if more than one bucket in the list 'buckets'
7143  * have the same bucket id. Returns false otherwise. */
7144 bool
7145 ofputil_bucket_check_duplicate_id(const struct ovs_list *buckets)
7146 {
7147     struct ofputil_bucket *i, *j;
7148
7149     LIST_FOR_EACH (i, list_node, buckets) {
7150         LIST_FOR_EACH_REVERSE (j, list_node, buckets) {
7151             if (i == j) {
7152                 break;
7153             }
7154             if (i->bucket_id == j->bucket_id) {
7155                 return true;
7156             }
7157         }
7158     }
7159
7160     return false;
7161 }
7162
7163 /* Returns the bucket at the front of the list 'buckets'.
7164  * Undefined if 'buckets is empty. */
7165 struct ofputil_bucket *
7166 ofputil_bucket_list_front(const struct ovs_list *buckets)
7167 {
7168     static struct ofputil_bucket *bucket;
7169
7170     ASSIGN_CONTAINER(bucket, list_front(buckets), list_node);
7171
7172     return bucket;
7173 }
7174
7175 /* Returns the bucket at the back of the list 'buckets'.
7176  * Undefined if 'buckets is empty. */
7177 struct ofputil_bucket *
7178 ofputil_bucket_list_back(const struct ovs_list *buckets)
7179 {
7180     static struct ofputil_bucket *bucket;
7181
7182     ASSIGN_CONTAINER(bucket, list_back(buckets), list_node);
7183
7184     return bucket;
7185 }
7186
7187 /* Returns an OpenFlow group stats request for OpenFlow version 'ofp_version',
7188  * that requests stats for group 'group_id'.  (Use OFPG_ALL to request stats
7189  * for all groups.)
7190  *
7191  * Group statistics include packet and byte counts for each group. */
7192 struct ofpbuf *
7193 ofputil_encode_group_stats_request(enum ofp_version ofp_version,
7194                                    uint32_t group_id)
7195 {
7196     struct ofpbuf *request;
7197
7198     switch (ofp_version) {
7199     case OFP10_VERSION:
7200         ovs_fatal(0, "dump-group-stats needs OpenFlow 1.1 or later "
7201                      "(\'-O OpenFlow11\')");
7202     case OFP11_VERSION:
7203     case OFP12_VERSION:
7204     case OFP13_VERSION:
7205     case OFP14_VERSION:
7206     case OFP15_VERSION: {
7207         struct ofp11_group_stats_request *req;
7208         request = ofpraw_alloc(OFPRAW_OFPST11_GROUP_REQUEST, ofp_version, 0);
7209         req = ofpbuf_put_zeros(request, sizeof *req);
7210         req->group_id = htonl(group_id);
7211         break;
7212     }
7213     default:
7214         OVS_NOT_REACHED();
7215     }
7216
7217     return request;
7218 }
7219
7220 void
7221 ofputil_uninit_group_desc(struct ofputil_group_desc *gd)
7222 {
7223     ofputil_bucket_list_destroy(&gd->buckets);
7224     free(&gd->props.fields);
7225 }
7226
7227 /* Decodes the OpenFlow group description request in 'oh', returning the group
7228  * whose description is requested, or OFPG_ALL if stats for all groups was
7229  * requested. */
7230 uint32_t
7231 ofputil_decode_group_desc_request(const struct ofp_header *oh)
7232 {
7233     struct ofpbuf request;
7234     enum ofpraw raw;
7235
7236     ofpbuf_use_const(&request, oh, ntohs(oh->length));
7237     raw = ofpraw_pull_assert(&request);
7238     if (raw == OFPRAW_OFPST11_GROUP_DESC_REQUEST) {
7239         return OFPG_ALL;
7240     } else if (raw == OFPRAW_OFPST15_GROUP_DESC_REQUEST) {
7241         ovs_be32 *group_id = ofpbuf_pull(&request, sizeof *group_id);
7242         return ntohl(*group_id);
7243     } else {
7244         OVS_NOT_REACHED();
7245     }
7246 }
7247
7248 /* Returns an OpenFlow group description request for OpenFlow version
7249  * 'ofp_version', that requests stats for group 'group_id'.  Use OFPG_ALL to
7250  * request stats for all groups (OpenFlow 1.4 and earlier always request all
7251  * groups).
7252  *
7253  * Group descriptions include the bucket and action configuration for each
7254  * group. */
7255 struct ofpbuf *
7256 ofputil_encode_group_desc_request(enum ofp_version ofp_version,
7257                                   uint32_t group_id)
7258 {
7259     struct ofpbuf *request;
7260     ovs_be32 gid;
7261
7262     switch (ofp_version) {
7263     case OFP10_VERSION:
7264         ovs_fatal(0, "dump-groups needs OpenFlow 1.1 or later "
7265                      "(\'-O OpenFlow11\')");
7266     case OFP11_VERSION:
7267     case OFP12_VERSION:
7268     case OFP13_VERSION:
7269     case OFP14_VERSION:
7270         request = ofpraw_alloc(OFPRAW_OFPST11_GROUP_DESC_REQUEST,
7271                                ofp_version, 0);
7272         break;
7273     case OFP15_VERSION:
7274         request = ofpraw_alloc(OFPRAW_OFPST15_GROUP_DESC_REQUEST,
7275                                ofp_version, 0);
7276         gid = htonl(group_id);
7277         ofpbuf_put(request, &gid, sizeof gid);
7278         break;
7279     default:
7280         OVS_NOT_REACHED();
7281     }
7282
7283     return request;
7284 }
7285
7286 static void
7287 ofputil_group_bucket_counters_to_ofp11(const struct ofputil_group_stats *gs,
7288                                     struct ofp11_bucket_counter bucket_cnts[])
7289 {
7290     int i;
7291
7292     for (i = 0; i < gs->n_buckets; i++) {
7293        bucket_cnts[i].packet_count = htonll(gs->bucket_stats[i].packet_count);
7294        bucket_cnts[i].byte_count = htonll(gs->bucket_stats[i].byte_count);
7295     }
7296 }
7297
7298 static void
7299 ofputil_group_stats_to_ofp11(const struct ofputil_group_stats *gs,
7300                              struct ofp11_group_stats *gs11, size_t length,
7301                              struct ofp11_bucket_counter bucket_cnts[])
7302 {
7303     memset(gs11, 0, sizeof *gs11);
7304     gs11->length = htons(length);
7305     gs11->group_id = htonl(gs->group_id);
7306     gs11->ref_count = htonl(gs->ref_count);
7307     gs11->packet_count = htonll(gs->packet_count);
7308     gs11->byte_count = htonll(gs->byte_count);
7309     ofputil_group_bucket_counters_to_ofp11(gs, bucket_cnts);
7310 }
7311
7312 static void
7313 ofputil_group_stats_to_ofp13(const struct ofputil_group_stats *gs,
7314                              struct ofp13_group_stats *gs13, size_t length,
7315                              struct ofp11_bucket_counter bucket_cnts[])
7316 {
7317     ofputil_group_stats_to_ofp11(gs, &gs13->gs, length, bucket_cnts);
7318     gs13->duration_sec = htonl(gs->duration_sec);
7319     gs13->duration_nsec = htonl(gs->duration_nsec);
7320
7321 }
7322
7323 /* Encodes 'gs' properly for the format of the list of group statistics
7324  * replies already begun in 'replies' and appends it to the list.  'replies'
7325  * must have originally been initialized with ofpmp_init(). */
7326 void
7327 ofputil_append_group_stats(struct ovs_list *replies,
7328                            const struct ofputil_group_stats *gs)
7329 {
7330     size_t bucket_counter_size;
7331     struct ofp11_bucket_counter *bucket_counters;
7332     size_t length;
7333
7334     bucket_counter_size = gs->n_buckets * sizeof(struct ofp11_bucket_counter);
7335
7336     switch (ofpmp_version(replies)) {
7337     case OFP11_VERSION:
7338     case OFP12_VERSION:{
7339             struct ofp11_group_stats *gs11;
7340
7341             length = sizeof *gs11 + bucket_counter_size;
7342             gs11 = ofpmp_append(replies, length);
7343             bucket_counters = (struct ofp11_bucket_counter *)(gs11 + 1);
7344             ofputil_group_stats_to_ofp11(gs, gs11, length, bucket_counters);
7345             break;
7346         }
7347
7348     case OFP13_VERSION:
7349     case OFP14_VERSION:
7350     case OFP15_VERSION: {
7351             struct ofp13_group_stats *gs13;
7352
7353             length = sizeof *gs13 + bucket_counter_size;
7354             gs13 = ofpmp_append(replies, length);
7355             bucket_counters = (struct ofp11_bucket_counter *)(gs13 + 1);
7356             ofputil_group_stats_to_ofp13(gs, gs13, length, bucket_counters);
7357             break;
7358         }
7359
7360     case OFP10_VERSION:
7361     default:
7362         OVS_NOT_REACHED();
7363     }
7364 }
7365 /* Returns an OpenFlow group features request for OpenFlow version
7366  * 'ofp_version'. */
7367 struct ofpbuf *
7368 ofputil_encode_group_features_request(enum ofp_version ofp_version)
7369 {
7370     struct ofpbuf *request = NULL;
7371
7372     switch (ofp_version) {
7373     case OFP10_VERSION:
7374     case OFP11_VERSION:
7375         ovs_fatal(0, "dump-group-features needs OpenFlow 1.2 or later "
7376                      "(\'-O OpenFlow12\')");
7377     case OFP12_VERSION:
7378     case OFP13_VERSION:
7379     case OFP14_VERSION:
7380     case OFP15_VERSION:
7381         request = ofpraw_alloc(OFPRAW_OFPST12_GROUP_FEATURES_REQUEST,
7382                                ofp_version, 0);
7383         break;
7384     default:
7385         OVS_NOT_REACHED();
7386     }
7387
7388     return request;
7389 }
7390
7391 /* Returns a OpenFlow message that encodes 'features' properly as a reply to
7392  * group features request 'request'. */
7393 struct ofpbuf *
7394 ofputil_encode_group_features_reply(
7395     const struct ofputil_group_features *features,
7396     const struct ofp_header *request)
7397 {
7398     struct ofp12_group_features_stats *ogf;
7399     struct ofpbuf *reply;
7400     int i;
7401
7402     reply = ofpraw_alloc_xid(OFPRAW_OFPST12_GROUP_FEATURES_REPLY,
7403                              request->version, request->xid, 0);
7404     ogf = ofpbuf_put_zeros(reply, sizeof *ogf);
7405     ogf->types = htonl(features->types);
7406     ogf->capabilities = htonl(features->capabilities);
7407     for (i = 0; i < OFPGT12_N_TYPES; i++) {
7408         ogf->max_groups[i] = htonl(features->max_groups[i]);
7409         ogf->actions[i] = ofpact_bitmap_to_openflow(features->ofpacts[i],
7410                                                     request->version);
7411     }
7412
7413     return reply;
7414 }
7415
7416 /* Decodes group features reply 'oh' into 'features'. */
7417 void
7418 ofputil_decode_group_features_reply(const struct ofp_header *oh,
7419                                     struct ofputil_group_features *features)
7420 {
7421     const struct ofp12_group_features_stats *ogf = ofpmsg_body(oh);
7422     int i;
7423
7424     features->types = ntohl(ogf->types);
7425     features->capabilities = ntohl(ogf->capabilities);
7426     for (i = 0; i < OFPGT12_N_TYPES; i++) {
7427         features->max_groups[i] = ntohl(ogf->max_groups[i]);
7428         features->ofpacts[i] = ofpact_bitmap_from_openflow(
7429             ogf->actions[i], oh->version);
7430     }
7431 }
7432
7433 /* Parse a group status request message into a 32 bit OpenFlow 1.1
7434  * group ID and stores the latter in '*group_id'.
7435  * Returns 0 if successful, otherwise an OFPERR_* number. */
7436 enum ofperr
7437 ofputil_decode_group_stats_request(const struct ofp_header *request,
7438                                    uint32_t *group_id)
7439 {
7440     const struct ofp11_group_stats_request *gsr11 = ofpmsg_body(request);
7441     *group_id = ntohl(gsr11->group_id);
7442     return 0;
7443 }
7444
7445 /* Converts a group stats reply in 'msg' into an abstract ofputil_group_stats
7446  * in 'gs'.  Assigns freshly allocated memory to gs->bucket_stats for the
7447  * caller to eventually free.
7448  *
7449  * Multiple group stats replies can be packed into a single OpenFlow message.
7450  * Calling this function multiple times for a single 'msg' iterates through the
7451  * replies.  The caller must initially leave 'msg''s layer pointers null and
7452  * not modify them between calls.
7453  *
7454  * Returns 0 if successful, EOF if no replies were left in this 'msg',
7455  * otherwise a positive errno value. */
7456 int
7457 ofputil_decode_group_stats_reply(struct ofpbuf *msg,
7458                                  struct ofputil_group_stats *gs)
7459 {
7460     struct ofp11_bucket_counter *obc;
7461     struct ofp11_group_stats *ogs11;
7462     enum ofpraw raw;
7463     enum ofperr error;
7464     size_t base_len;
7465     size_t length;
7466     size_t i;
7467
7468     gs->bucket_stats = NULL;
7469     error = (msg->header ? ofpraw_decode(&raw, msg->header)
7470              : ofpraw_pull(&raw, msg));
7471     if (error) {
7472         return error;
7473     }
7474
7475     if (!msg->size) {
7476         return EOF;
7477     }
7478
7479     if (raw == OFPRAW_OFPST11_GROUP_REPLY) {
7480         base_len = sizeof *ogs11;
7481         ogs11 = ofpbuf_try_pull(msg, sizeof *ogs11);
7482         gs->duration_sec = gs->duration_nsec = UINT32_MAX;
7483     } else if (raw == OFPRAW_OFPST13_GROUP_REPLY) {
7484         struct ofp13_group_stats *ogs13;
7485
7486         base_len = sizeof *ogs13;
7487         ogs13 = ofpbuf_try_pull(msg, sizeof *ogs13);
7488         if (ogs13) {
7489             ogs11 = &ogs13->gs;
7490             gs->duration_sec = ntohl(ogs13->duration_sec);
7491             gs->duration_nsec = ntohl(ogs13->duration_nsec);
7492         } else {
7493             ogs11 = NULL;
7494         }
7495     } else {
7496         OVS_NOT_REACHED();
7497     }
7498
7499     if (!ogs11) {
7500         VLOG_WARN_RL(&bad_ofmsg_rl, "%s reply has %"PRIu32" leftover bytes at end",
7501                      ofpraw_get_name(raw), msg->size);
7502         return OFPERR_OFPBRC_BAD_LEN;
7503     }
7504     length = ntohs(ogs11->length);
7505     if (length < sizeof base_len) {
7506         VLOG_WARN_RL(&bad_ofmsg_rl, "%s reply claims invalid length %"PRIuSIZE,
7507                      ofpraw_get_name(raw), length);
7508         return OFPERR_OFPBRC_BAD_LEN;
7509     }
7510
7511     gs->group_id = ntohl(ogs11->group_id);
7512     gs->ref_count = ntohl(ogs11->ref_count);
7513     gs->packet_count = ntohll(ogs11->packet_count);
7514     gs->byte_count = ntohll(ogs11->byte_count);
7515
7516     gs->n_buckets = (length - base_len) / sizeof *obc;
7517     obc = ofpbuf_try_pull(msg, gs->n_buckets * sizeof *obc);
7518     if (!obc) {
7519         VLOG_WARN_RL(&bad_ofmsg_rl, "%s reply has %"PRIu32" leftover bytes at end",
7520                      ofpraw_get_name(raw), msg->size);
7521         return OFPERR_OFPBRC_BAD_LEN;
7522     }
7523
7524     gs->bucket_stats = xmalloc(gs->n_buckets * sizeof *gs->bucket_stats);
7525     for (i = 0; i < gs->n_buckets; i++) {
7526         gs->bucket_stats[i].packet_count = ntohll(obc[i].packet_count);
7527         gs->bucket_stats[i].byte_count = ntohll(obc[i].byte_count);
7528     }
7529
7530     return 0;
7531 }
7532
7533 static void
7534 ofputil_put_ofp11_bucket(const struct ofputil_bucket *bucket,
7535                          struct ofpbuf *openflow, enum ofp_version ofp_version)
7536 {
7537     struct ofp11_bucket *ob;
7538     size_t start;
7539
7540     start = openflow->size;
7541     ofpbuf_put_zeros(openflow, sizeof *ob);
7542     ofpacts_put_openflow_actions(bucket->ofpacts, bucket->ofpacts_len,
7543                                 openflow, ofp_version);
7544     ob = ofpbuf_at_assert(openflow, start, sizeof *ob);
7545     ob->len = htons(openflow->size - start);
7546     ob->weight = htons(bucket->weight);
7547     ob->watch_port = ofputil_port_to_ofp11(bucket->watch_port);
7548     ob->watch_group = htonl(bucket->watch_group);
7549 }
7550
7551 static void
7552 ofputil_put_ofp15_group_bucket_prop_weight(ovs_be16 weight,
7553                                            struct ofpbuf *openflow)
7554 {
7555     size_t start_ofs;
7556     struct ofp15_group_bucket_prop_weight *prop;
7557
7558     start_ofs = start_property(openflow, OFPGBPT15_WEIGHT);
7559     ofpbuf_put_zeros(openflow, sizeof *prop - sizeof(struct ofp_prop_header));
7560     prop = ofpbuf_at_assert(openflow, start_ofs, sizeof *prop);
7561     prop->weight = weight;
7562     end_property(openflow, start_ofs);
7563 }
7564
7565 static void
7566 ofputil_put_ofp15_group_bucket_prop_watch(ovs_be32 watch, uint16_t type,
7567                                           struct ofpbuf *openflow)
7568 {
7569     size_t start_ofs;
7570     struct ofp15_group_bucket_prop_watch *prop;
7571
7572     start_ofs = start_property(openflow, type);
7573     ofpbuf_put_zeros(openflow, sizeof *prop - sizeof(struct ofp_prop_header));
7574     prop = ofpbuf_at_assert(openflow, start_ofs, sizeof *prop);
7575     prop->watch = watch;
7576     end_property(openflow, start_ofs);
7577 }
7578
7579 static void
7580 ofputil_put_ofp15_bucket(const struct ofputil_bucket *bucket,
7581                          uint32_t bucket_id, enum ofp11_group_type group_type,
7582                          struct ofpbuf *openflow, enum ofp_version ofp_version)
7583 {
7584     struct ofp15_bucket *ob;
7585     size_t start, actions_start, actions_len;
7586
7587     start = openflow->size;
7588     ofpbuf_put_zeros(openflow, sizeof *ob);
7589
7590     actions_start = openflow->size;
7591     ofpacts_put_openflow_actions(bucket->ofpacts, bucket->ofpacts_len,
7592                                  openflow, ofp_version);
7593     actions_len = openflow->size - actions_start;
7594
7595     if (group_type == OFPGT11_SELECT) {
7596         ofputil_put_ofp15_group_bucket_prop_weight(htons(bucket->weight),
7597                                                    openflow);
7598     }
7599     if (bucket->watch_port != OFPP_ANY) {
7600         ovs_be32 port = ofputil_port_to_ofp11(bucket->watch_port);
7601         ofputil_put_ofp15_group_bucket_prop_watch(port,
7602                                                   OFPGBPT15_WATCH_PORT,
7603                                                   openflow);
7604     }
7605     if (bucket->watch_group != OFPG_ANY) {
7606         ovs_be32 group = htonl(bucket->watch_group);
7607         ofputil_put_ofp15_group_bucket_prop_watch(group,
7608                                                   OFPGBPT15_WATCH_GROUP,
7609                                                   openflow);
7610     }
7611
7612     ob = ofpbuf_at_assert(openflow, start, sizeof *ob);
7613     ob->len = htons(openflow->size - start);
7614     ob->action_array_len = htons(actions_len);
7615     ob->bucket_id = htonl(bucket_id);
7616 }
7617
7618 static void
7619 ofputil_put_group_prop_ntr_selection_method(enum ofp_version ofp_version,
7620                                             const struct ofputil_group_props *gp,
7621                                             struct ofpbuf *openflow)
7622 {
7623     struct ntr_group_prop_selection_method *prop;
7624     size_t start;
7625
7626     start = openflow->size;
7627     ofpbuf_put_zeros(openflow, sizeof *prop);
7628     oxm_put_field_array(openflow, &gp->fields, ofp_version);
7629     prop = ofpbuf_at_assert(openflow, start, sizeof *prop);
7630     prop->type = htons(OFPGPT15_EXPERIMENTER);
7631     prop->experimenter = htonl(NTR_VENDOR_ID);
7632     prop->exp_type = htonl(NTRT_SELECTION_METHOD);
7633     strcpy(prop->selection_method, gp->selection_method);
7634     prop->selection_method_param = htonll(gp->selection_method_param);
7635     end_property(openflow, start);
7636 }
7637
7638 static void
7639 ofputil_append_ofp11_group_desc_reply(const struct ofputil_group_desc *gds,
7640                                       const struct ovs_list *buckets,
7641                                       struct ovs_list *replies,
7642                                       enum ofp_version version)
7643 {
7644     struct ofpbuf *reply = ofpbuf_from_list(list_back(replies));
7645     struct ofp11_group_desc_stats *ogds;
7646     struct ofputil_bucket *bucket;
7647     size_t start_ogds;
7648
7649     start_ogds = reply->size;
7650     ofpbuf_put_zeros(reply, sizeof *ogds);
7651     LIST_FOR_EACH (bucket, list_node, buckets) {
7652         ofputil_put_ofp11_bucket(bucket, reply, version);
7653     }
7654     ogds = ofpbuf_at_assert(reply, start_ogds, sizeof *ogds);
7655     ogds->length = htons(reply->size - start_ogds);
7656     ogds->type = gds->type;
7657     ogds->group_id = htonl(gds->group_id);
7658
7659     ofpmp_postappend(replies, start_ogds);
7660 }
7661
7662 static void
7663 ofputil_append_ofp15_group_desc_reply(const struct ofputil_group_desc *gds,
7664                                       const struct ovs_list *buckets,
7665                                       struct ovs_list *replies,
7666                                       enum ofp_version version)
7667 {
7668     struct ofpbuf *reply = ofpbuf_from_list(list_back(replies));
7669     struct ofp15_group_desc_stats *ogds;
7670     struct ofputil_bucket *bucket;
7671     size_t start_ogds, start_buckets;
7672
7673     start_ogds = reply->size;
7674     ofpbuf_put_zeros(reply, sizeof *ogds);
7675     start_buckets = reply->size;
7676     LIST_FOR_EACH (bucket, list_node, buckets) {
7677         ofputil_put_ofp15_bucket(bucket, bucket->bucket_id,
7678                                  gds->type, reply, version);
7679     }
7680     ogds = ofpbuf_at_assert(reply, start_ogds, sizeof *ogds);
7681     ogds->length = htons(reply->size - start_ogds);
7682     ogds->type = gds->type;
7683     ogds->group_id = htonl(gds->group_id);
7684     ogds->bucket_list_len =  htons(reply->size - start_buckets);
7685
7686     /* Add group properties */
7687     if (gds->props.selection_method[0]) {
7688         ofputil_put_group_prop_ntr_selection_method(version, &gds->props,
7689                                                     reply);
7690     }
7691
7692     ofpmp_postappend(replies, start_ogds);
7693 }
7694
7695 /* Appends a group stats reply that contains the data in 'gds' to those already
7696  * present in the list of ofpbufs in 'replies'.  'replies' should have been
7697  * initialized with ofpmp_init(). */
7698 void
7699 ofputil_append_group_desc_reply(const struct ofputil_group_desc *gds,
7700                                 const struct ovs_list *buckets,
7701                                 struct ovs_list *replies)
7702 {
7703     enum ofp_version version = ofpmp_version(replies);
7704
7705     switch (version)
7706     {
7707     case OFP11_VERSION:
7708     case OFP12_VERSION:
7709     case OFP13_VERSION:
7710     case OFP14_VERSION:
7711         ofputil_append_ofp11_group_desc_reply(gds, buckets, replies, version);
7712         break;
7713
7714     case OFP15_VERSION:
7715         ofputil_append_ofp15_group_desc_reply(gds, buckets, replies, version);
7716         break;
7717
7718     case OFP10_VERSION:
7719     default:
7720         OVS_NOT_REACHED();
7721     }
7722 }
7723
7724 static enum ofperr
7725 ofputil_pull_ofp11_buckets(struct ofpbuf *msg, size_t buckets_length,
7726                            enum ofp_version version, struct ovs_list *buckets)
7727 {
7728     struct ofp11_bucket *ob;
7729     uint32_t bucket_id = 0;
7730
7731     list_init(buckets);
7732     while (buckets_length > 0) {
7733         struct ofputil_bucket *bucket;
7734         struct ofpbuf ofpacts;
7735         enum ofperr error;
7736         size_t ob_len;
7737
7738         ob = (buckets_length >= sizeof *ob
7739               ? ofpbuf_try_pull(msg, sizeof *ob)
7740               : NULL);
7741         if (!ob) {
7742             VLOG_WARN_RL(&bad_ofmsg_rl, "buckets end with %"PRIuSIZE" leftover bytes",
7743                          buckets_length);
7744             return OFPERR_OFPGMFC_BAD_BUCKET;
7745         }
7746
7747         ob_len = ntohs(ob->len);
7748         if (ob_len < sizeof *ob) {
7749             VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message bucket length "
7750                          "%"PRIuSIZE" is not valid", ob_len);
7751             return OFPERR_OFPGMFC_BAD_BUCKET;
7752         } else if (ob_len > buckets_length) {
7753             VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message bucket length "
7754                          "%"PRIuSIZE" exceeds remaining buckets data size %"PRIuSIZE,
7755                          ob_len, buckets_length);
7756             return OFPERR_OFPGMFC_BAD_BUCKET;
7757         }
7758         buckets_length -= ob_len;
7759
7760         ofpbuf_init(&ofpacts, 0);
7761         error = ofpacts_pull_openflow_actions(msg, ob_len - sizeof *ob,
7762                                               version, &ofpacts);
7763         if (error) {
7764             ofpbuf_uninit(&ofpacts);
7765             ofputil_bucket_list_destroy(buckets);
7766             return error;
7767         }
7768
7769         bucket = xzalloc(sizeof *bucket);
7770         bucket->weight = ntohs(ob->weight);
7771         error = ofputil_port_from_ofp11(ob->watch_port, &bucket->watch_port);
7772         if (error) {
7773             ofpbuf_uninit(&ofpacts);
7774             ofputil_bucket_list_destroy(buckets);
7775             return OFPERR_OFPGMFC_BAD_WATCH;
7776         }
7777         bucket->watch_group = ntohl(ob->watch_group);
7778         bucket->bucket_id = bucket_id++;
7779
7780         bucket->ofpacts = ofpbuf_steal_data(&ofpacts);
7781         bucket->ofpacts_len = ofpacts.size;
7782         list_push_back(buckets, &bucket->list_node);
7783     }
7784
7785     return 0;
7786 }
7787
7788 static enum ofperr
7789 parse_ofp15_group_bucket_prop_weight(const struct ofpbuf *payload,
7790                                      ovs_be16 *weight)
7791 {
7792     struct ofp15_group_bucket_prop_weight *prop = payload->data;
7793
7794     if (payload->size != sizeof *prop) {
7795         log_property(false, "OpenFlow bucket weight property length "
7796                      "%u is not valid", payload->size);
7797         return OFPERR_OFPBPC_BAD_LEN;
7798     }
7799
7800     *weight = prop->weight;
7801
7802     return 0;
7803 }
7804
7805 static enum ofperr
7806 parse_ofp15_group_bucket_prop_watch(const struct ofpbuf *payload,
7807                                     ovs_be32 *watch)
7808 {
7809     struct ofp15_group_bucket_prop_watch *prop = payload->data;
7810
7811     if (payload->size != sizeof *prop) {
7812         log_property(false, "OpenFlow bucket watch port or group "
7813                      "property length %u is not valid", payload->size);
7814         return OFPERR_OFPBPC_BAD_LEN;
7815     }
7816
7817     *watch = prop->watch;
7818
7819     return 0;
7820 }
7821
7822 static enum ofperr
7823 ofputil_pull_ofp15_buckets(struct ofpbuf *msg, size_t buckets_length,
7824                            enum ofp_version version, uint8_t group_type,
7825                            struct ovs_list *buckets)
7826 {
7827     struct ofp15_bucket *ob;
7828
7829     list_init(buckets);
7830     while (buckets_length > 0) {
7831         struct ofputil_bucket *bucket = NULL;
7832         struct ofpbuf ofpacts;
7833         enum ofperr err = OFPERR_OFPGMFC_BAD_BUCKET;
7834         struct ofpbuf properties;
7835         size_t ob_len, actions_len, properties_len;
7836         ovs_be32 watch_port = ofputil_port_to_ofp11(OFPP_ANY);
7837         ovs_be32 watch_group = htonl(OFPG_ANY);
7838         ovs_be16 weight = htons(group_type == OFPGT11_SELECT ? 1 : 0);
7839
7840         ofpbuf_init(&ofpacts, 0);
7841
7842         ob = ofpbuf_try_pull(msg, sizeof *ob);
7843         if (!ob) {
7844             VLOG_WARN_RL(&bad_ofmsg_rl, "buckets end with %"PRIuSIZE
7845                          " leftover bytes", buckets_length);
7846             goto err;
7847         }
7848
7849         ob_len = ntohs(ob->len);
7850         actions_len = ntohs(ob->action_array_len);
7851
7852         if (ob_len < sizeof *ob) {
7853             VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message bucket length "
7854                          "%"PRIuSIZE" is not valid", ob_len);
7855             goto err;
7856         } else if (ob_len > buckets_length) {
7857             VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message bucket length "
7858                          "%"PRIuSIZE" exceeds remaining buckets data size %"
7859                          PRIuSIZE, ob_len, buckets_length);
7860             goto err;
7861         } else if (actions_len > ob_len - sizeof *ob) {
7862             VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message bucket actions "
7863                          "length %"PRIuSIZE" exceeds remaining bucket "
7864                          "data size %"PRIuSIZE, actions_len,
7865                          ob_len - sizeof *ob);
7866             goto err;
7867         }
7868         buckets_length -= ob_len;
7869
7870         err = ofpacts_pull_openflow_actions(msg, actions_len, version,
7871                                             &ofpacts);
7872         if (err) {
7873             goto err;
7874         }
7875
7876         properties_len = ob_len - sizeof *ob - actions_len;
7877         ofpbuf_use_const(&properties, ofpbuf_pull(msg, properties_len),
7878                          properties_len);
7879
7880         while (properties.size > 0) {
7881             struct ofpbuf payload;
7882             uint16_t type;
7883
7884             err = ofputil_pull_property(&properties, &payload, &type);
7885             if (err) {
7886                 goto err;
7887             }
7888
7889             switch (type) {
7890             case OFPGBPT15_WEIGHT:
7891                 err = parse_ofp15_group_bucket_prop_weight(&payload, &weight);
7892                 break;
7893
7894             case OFPGBPT15_WATCH_PORT:
7895                 err = parse_ofp15_group_bucket_prop_watch(&payload,
7896                                                           &watch_port);
7897                 break;
7898
7899             case OFPGBPT15_WATCH_GROUP:
7900                 err = parse_ofp15_group_bucket_prop_watch(&payload,
7901                                                           &watch_group);
7902                 break;
7903
7904             default:
7905                 log_property(false, "unknown group bucket property %"PRIu16,
7906                              type);
7907                 err = OFPERR_OFPBPC_BAD_TYPE;
7908                 break;
7909             }
7910
7911             if (err) {
7912                 goto err;
7913             }
7914         }
7915
7916         bucket = xzalloc(sizeof *bucket);
7917
7918         bucket->weight = ntohs(weight);
7919         err = ofputil_port_from_ofp11(watch_port, &bucket->watch_port);
7920         if (err) {
7921             err = OFPERR_OFPGMFC_BAD_WATCH;
7922             goto err;
7923         }
7924         bucket->watch_group = ntohl(watch_group);
7925         bucket->bucket_id = ntohl(ob->bucket_id);
7926         if (bucket->bucket_id > OFPG15_BUCKET_MAX) {
7927             VLOG_WARN_RL(&bad_ofmsg_rl, "bucket id (%u) is out of range",
7928                          bucket->bucket_id);
7929             err = OFPERR_OFPGMFC_BAD_BUCKET;
7930             goto err;
7931         }
7932
7933         bucket->ofpacts = ofpbuf_steal_data(&ofpacts);
7934         bucket->ofpacts_len = ofpacts.size;
7935         list_push_back(buckets, &bucket->list_node);
7936
7937         continue;
7938
7939     err:
7940         free(bucket);
7941         ofpbuf_uninit(&ofpacts);
7942         ofputil_bucket_list_destroy(buckets);
7943         return err;
7944     }
7945
7946     if (ofputil_bucket_check_duplicate_id(buckets)) {
7947         VLOG_WARN_RL(&bad_ofmsg_rl, "Duplicate bucket id");
7948         ofputil_bucket_list_destroy(buckets);
7949         return OFPERR_OFPGMFC_BAD_BUCKET;
7950     }
7951
7952     return 0;
7953 }
7954
7955 static void
7956 ofputil_init_group_properties(struct ofputil_group_props *gp)
7957 {
7958     memset(gp, 0, sizeof *gp);
7959 }
7960
7961 static enum ofperr
7962 parse_group_prop_ntr_selection_method(struct ofpbuf *payload,
7963                                       enum ofp11_group_type group_type,
7964                                       enum ofp15_group_mod_command group_cmd,
7965                                       struct ofputil_group_props *gp)
7966 {
7967     struct ntr_group_prop_selection_method *prop = payload->data;
7968     size_t fields_len, method_len;
7969     enum ofperr error;
7970
7971     switch (group_type) {
7972     case OFPGT11_SELECT:
7973         break;
7974     case OFPGT11_ALL:
7975     case OFPGT11_INDIRECT:
7976     case OFPGT11_FF:
7977         log_property(false, "ntr selection method property is only allowed "
7978                      "for select groups");
7979         return OFPERR_OFPBPC_BAD_VALUE;
7980     default:
7981         OVS_NOT_REACHED();
7982     }
7983
7984     switch (group_cmd) {
7985     case OFPGC15_ADD:
7986     case OFPGC15_MODIFY:
7987         break;
7988     case OFPGC15_DELETE:
7989     case OFPGC15_INSERT_BUCKET:
7990     case OFPGC15_REMOVE_BUCKET:
7991         log_property(false, "ntr selection method property is only allowed "
7992                      "for add and delete group modifications");
7993         return OFPERR_OFPBPC_BAD_VALUE;
7994     default:
7995         OVS_NOT_REACHED();
7996     }
7997
7998     if (payload->size < sizeof *prop) {
7999         log_property(false, "ntr selection method property length "
8000                      "%u is not valid", payload->size);
8001         return OFPERR_OFPBPC_BAD_LEN;
8002     }
8003
8004     method_len = strnlen(prop->selection_method, NTR_MAX_SELECTION_METHOD_LEN);
8005
8006     if (method_len == NTR_MAX_SELECTION_METHOD_LEN) {
8007         log_property(false, "ntr selection method is not null terminated");
8008         return OFPERR_OFPBPC_BAD_VALUE;
8009     }
8010
8011     if (strcmp("hash", prop->selection_method)) {
8012         log_property(false, "ntr selection method '%s' is not supported",
8013                      prop->selection_method);
8014         return OFPERR_OFPBPC_BAD_VALUE;
8015     }
8016
8017     strcpy(gp->selection_method, prop->selection_method);
8018     gp->selection_method_param = ntohll(prop->selection_method_param);
8019
8020     if (!method_len && gp->selection_method_param) {
8021         log_property(false, "ntr selection method parameter is non-zero but "
8022                      "selection method is empty");
8023         return OFPERR_OFPBPC_BAD_VALUE;
8024     }
8025
8026     ofpbuf_pull(payload, sizeof *prop);
8027
8028     fields_len = ntohs(prop->length) - sizeof *prop;
8029     if (!method_len && fields_len) {
8030         log_property(false, "ntr selection method parameter is zero "
8031                      "but fields are provided");
8032         return OFPERR_OFPBPC_BAD_VALUE;
8033     }
8034
8035     error = oxm_pull_field_array(payload->data, fields_len,
8036                                  &gp->fields);
8037     if (error) {
8038         log_property(false, "ntr selection method fields are invalid");
8039         return error;
8040     }
8041
8042     return 0;
8043 }
8044
8045 static enum ofperr
8046 parse_group_prop_ntr(struct ofpbuf *payload, uint32_t exp_type,
8047                      enum ofp11_group_type group_type,
8048                      enum ofp15_group_mod_command group_cmd,
8049                      struct ofputil_group_props *gp)
8050 {
8051     enum ofperr error;
8052
8053     switch (exp_type) {
8054     case NTRT_SELECTION_METHOD:
8055         error = parse_group_prop_ntr_selection_method(payload, group_type,
8056                                                       group_cmd, gp);
8057         break;
8058
8059     default:
8060         log_property(false, "unknown group property ntr experimenter type "
8061                      "%"PRIu32, exp_type);
8062         error = OFPERR_OFPBPC_BAD_TYPE;
8063         break;
8064     }
8065
8066     return error;
8067 }
8068
8069 static enum ofperr
8070 parse_ofp15_group_prop_exp(struct ofpbuf *payload,
8071                            enum ofp11_group_type group_type,
8072                            enum ofp15_group_mod_command group_cmd,
8073                            struct ofputil_group_props *gp)
8074 {
8075     struct ofp_prop_experimenter *prop = payload->data;
8076     uint16_t experimenter;
8077     uint32_t exp_type;
8078     enum ofperr error;
8079
8080     if (payload->size < sizeof *prop) {
8081         return OFPERR_OFPBPC_BAD_LEN;
8082     }
8083
8084     experimenter = ntohl(prop->experimenter);
8085     exp_type = ntohl(prop->exp_type);
8086
8087     switch (experimenter) {
8088     case NTR_VENDOR_ID:
8089         error = parse_group_prop_ntr(payload, exp_type, group_type,
8090                                      group_cmd, gp);
8091         break;
8092
8093     default:
8094         log_property(false, "unknown group property experimenter %"PRIu16,
8095                      experimenter);
8096         error = OFPERR_OFPBPC_BAD_EXPERIMENTER;
8097         break;
8098     }
8099
8100     return error;
8101 }
8102
8103 static enum ofperr
8104 parse_ofp15_group_properties(struct ofpbuf *msg,
8105                              enum ofp11_group_type group_type,
8106                              enum ofp15_group_mod_command group_cmd,
8107                              struct ofputil_group_props *gp,
8108                              size_t properties_len)
8109 {
8110     struct ofpbuf properties;
8111
8112     ofpbuf_use_const(&properties, ofpbuf_pull(msg, properties_len),
8113                      properties_len);
8114
8115     while (properties.size > 0) {
8116         struct ofpbuf payload;
8117         enum ofperr error;
8118         uint16_t type;
8119
8120         error = ofputil_pull_property(&properties, &payload, &type);
8121         if (error) {
8122             return error;
8123         }
8124
8125         switch (type) {
8126         case OFPGPT15_EXPERIMENTER:
8127             error = parse_ofp15_group_prop_exp(&payload, group_type,
8128                                                group_cmd, gp);
8129             break;
8130
8131         default:
8132             log_property(false, "unknown group property %"PRIu16, type);
8133             error = OFPERR_OFPBPC_BAD_TYPE;
8134             break;
8135         }
8136
8137         if (error) {
8138             return error;
8139         }
8140     }
8141
8142     return 0;
8143 }
8144
8145 static int
8146 ofputil_decode_ofp11_group_desc_reply(struct ofputil_group_desc *gd,
8147                                       struct ofpbuf *msg,
8148                                       enum ofp_version version)
8149 {
8150     struct ofp11_group_desc_stats *ogds;
8151     size_t length;
8152
8153     if (!msg->header) {
8154         ofpraw_pull_assert(msg);
8155     }
8156
8157     if (!msg->size) {
8158         return EOF;
8159     }
8160
8161     ogds = ofpbuf_try_pull(msg, sizeof *ogds);
8162     if (!ogds) {
8163         VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST11_GROUP_DESC reply has %"PRIu32" "
8164                      "leftover bytes at end", msg->size);
8165         return OFPERR_OFPBRC_BAD_LEN;
8166     }
8167     gd->type = ogds->type;
8168     gd->group_id = ntohl(ogds->group_id);
8169
8170     length = ntohs(ogds->length);
8171     if (length < sizeof *ogds || length - sizeof *ogds > msg->size) {
8172         VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST11_GROUP_DESC reply claims invalid "
8173                      "length %"PRIuSIZE, length);
8174         return OFPERR_OFPBRC_BAD_LEN;
8175     }
8176
8177     return ofputil_pull_ofp11_buckets(msg, length - sizeof *ogds, version,
8178                                       &gd->buckets);
8179 }
8180
8181 static int
8182 ofputil_decode_ofp15_group_desc_reply(struct ofputil_group_desc *gd,
8183                                       struct ofpbuf *msg,
8184                                       enum ofp_version version)
8185 {
8186     struct ofp15_group_desc_stats *ogds;
8187     uint16_t length, bucket_list_len;
8188     int error;
8189
8190     if (!msg->header) {
8191         ofpraw_pull_assert(msg);
8192     }
8193
8194     if (!msg->size) {
8195         return EOF;
8196     }
8197
8198     ogds = ofpbuf_try_pull(msg, sizeof *ogds);
8199     if (!ogds) {
8200         VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST11_GROUP_DESC reply has %"PRIu32" "
8201                      "leftover bytes at end", msg->size);
8202         return OFPERR_OFPBRC_BAD_LEN;
8203     }
8204     gd->type = ogds->type;
8205     gd->group_id = ntohl(ogds->group_id);
8206
8207     length = ntohs(ogds->length);
8208     if (length < sizeof *ogds || length - sizeof *ogds > msg->size) {
8209         VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST11_GROUP_DESC reply claims invalid "
8210                      "length %u", length);
8211         return OFPERR_OFPBRC_BAD_LEN;
8212     }
8213
8214     bucket_list_len = ntohs(ogds->bucket_list_len);
8215     if (length < bucket_list_len + sizeof *ogds) {
8216         VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST11_GROUP_DESC reply claims invalid "
8217                      "bucket list length %u", bucket_list_len);
8218         return OFPERR_OFPBRC_BAD_LEN;
8219     }
8220     error = ofputil_pull_ofp15_buckets(msg, bucket_list_len, version, gd->type,
8221                                        &gd->buckets);
8222     if (error) {
8223         return error;
8224     }
8225
8226     /* By definition group desc messages don't have a group mod command.
8227      * However, parse_group_prop_ntr_selection_method() checks to make sure
8228      * that the command is OFPGC15_ADD or OFPGC15_DELETE to guard
8229      * against group mod messages with other commands supplying
8230      * a NTR selection method group experimenter property.
8231      * Such properties are valid for group desc replies so
8232      * claim that the group mod command is OFPGC15_ADD to
8233      * satisfy the check in parse_group_prop_ntr_selection_method() */
8234     return parse_ofp15_group_properties(msg, gd->type, OFPGC15_ADD, &gd->props,
8235                                         msg->size);
8236 }
8237
8238 /* Converts a group description reply in 'msg' into an abstract
8239  * ofputil_group_desc in 'gd'.
8240  *
8241  * Multiple group description replies can be packed into a single OpenFlow
8242  * message.  Calling this function multiple times for a single 'msg' iterates
8243  * through the replies.  The caller must initially leave 'msg''s layer pointers
8244  * null and not modify them between calls.
8245  *
8246  * Returns 0 if successful, EOF if no replies were left in this 'msg',
8247  * otherwise a positive errno value. */
8248 int
8249 ofputil_decode_group_desc_reply(struct ofputil_group_desc *gd,
8250                                 struct ofpbuf *msg, enum ofp_version version)
8251 {
8252     ofputil_init_group_properties(&gd->props);
8253
8254     switch (version)
8255     {
8256     case OFP11_VERSION:
8257     case OFP12_VERSION:
8258     case OFP13_VERSION:
8259     case OFP14_VERSION:
8260         return ofputil_decode_ofp11_group_desc_reply(gd, msg, version);
8261
8262     case OFP15_VERSION:
8263         return ofputil_decode_ofp15_group_desc_reply(gd, msg, version);
8264
8265     case OFP10_VERSION:
8266     default:
8267         OVS_NOT_REACHED();
8268     }
8269 }
8270
8271 void
8272 ofputil_uninit_group_mod(struct ofputil_group_mod *gm)
8273 {
8274     ofputil_bucket_list_destroy(&gm->buckets);
8275 }
8276
8277 static struct ofpbuf *
8278 ofputil_encode_ofp11_group_mod(enum ofp_version ofp_version,
8279                                const struct ofputil_group_mod *gm)
8280 {
8281     struct ofpbuf *b;
8282     struct ofp11_group_mod *ogm;
8283     size_t start_ogm;
8284     struct ofputil_bucket *bucket;
8285
8286     b = ofpraw_alloc(OFPRAW_OFPT11_GROUP_MOD, ofp_version, 0);
8287     start_ogm = b->size;
8288     ofpbuf_put_zeros(b, sizeof *ogm);
8289
8290     LIST_FOR_EACH (bucket, list_node, &gm->buckets) {
8291         ofputil_put_ofp11_bucket(bucket, b, ofp_version);
8292     }
8293     ogm = ofpbuf_at_assert(b, start_ogm, sizeof *ogm);
8294     ogm->command = htons(gm->command);
8295     ogm->type = gm->type;
8296     ogm->group_id = htonl(gm->group_id);
8297
8298     return b;
8299 }
8300
8301 static struct ofpbuf *
8302 ofputil_encode_ofp15_group_mod(enum ofp_version ofp_version,
8303                                const struct ofputil_group_mod *gm)
8304 {
8305     struct ofpbuf *b;
8306     struct ofp15_group_mod *ogm;
8307     size_t start_ogm;
8308     struct ofputil_bucket *bucket;
8309     struct id_pool *bucket_ids = NULL;
8310
8311     b = ofpraw_alloc(OFPRAW_OFPT15_GROUP_MOD, ofp_version, 0);
8312     start_ogm = b->size;
8313     ofpbuf_put_zeros(b, sizeof *ogm);
8314
8315     LIST_FOR_EACH (bucket, list_node, &gm->buckets) {
8316         uint32_t bucket_id;
8317
8318         /* Generate a bucket id if none was supplied */
8319         if (bucket->bucket_id > OFPG15_BUCKET_MAX) {
8320             if (!bucket_ids) {
8321                 const struct ofputil_bucket *bkt;
8322
8323                 bucket_ids = id_pool_create(0, OFPG15_BUCKET_MAX + 1);
8324
8325                 /* Mark all bucket_ids that are present in gm
8326                  * as used in the pool. */
8327                 LIST_FOR_EACH_REVERSE (bkt, list_node, &gm->buckets) {
8328                     if (bkt == bucket) {
8329                         break;
8330                     }
8331                     if (bkt->bucket_id <= OFPG15_BUCKET_MAX) {
8332                         id_pool_add(bucket_ids, bkt->bucket_id);
8333                     }
8334                 }
8335             }
8336
8337             if (!id_pool_alloc_id(bucket_ids, &bucket_id)) {
8338                 OVS_NOT_REACHED();
8339             }
8340         } else {
8341             bucket_id = bucket->bucket_id;
8342         }
8343
8344         ofputil_put_ofp15_bucket(bucket, bucket_id, gm->type, b, ofp_version);
8345     }
8346     ogm = ofpbuf_at_assert(b, start_ogm, sizeof *ogm);
8347     ogm->command = htons(gm->command);
8348     ogm->type = gm->type;
8349     ogm->group_id = htonl(gm->group_id);
8350     ogm->command_bucket_id = htonl(gm->command_bucket_id);
8351     ogm->bucket_array_len = htons(b->size - start_ogm - sizeof *ogm);
8352
8353     /* Add group properties */
8354     if (gm->props.selection_method[0]) {
8355         ofputil_put_group_prop_ntr_selection_method(ofp_version, &gm->props, b);
8356     }
8357
8358     id_pool_destroy(bucket_ids);
8359     return b;
8360 }
8361
8362 static void
8363 bad_group_cmd(enum ofp15_group_mod_command cmd)
8364 {
8365     const char *opt_version;
8366     const char *version;
8367     const char *cmd_str;
8368
8369     switch (cmd) {
8370     case OFPGC15_ADD:
8371     case OFPGC15_MODIFY:
8372     case OFPGC15_DELETE:
8373         version = "1.1";
8374         opt_version = "11";
8375         break;
8376
8377     case OFPGC15_INSERT_BUCKET:
8378     case OFPGC15_REMOVE_BUCKET:
8379         version = "1.5";
8380         opt_version = "15";
8381         break;
8382
8383     default:
8384         OVS_NOT_REACHED();
8385     }
8386
8387     switch (cmd) {
8388     case OFPGC15_ADD:
8389         cmd_str = "add-group";
8390         break;
8391
8392     case OFPGC15_MODIFY:
8393         cmd_str = "mod-group";
8394         break;
8395
8396     case OFPGC15_DELETE:
8397         cmd_str = "del-group";
8398         break;
8399
8400     case OFPGC15_INSERT_BUCKET:
8401         cmd_str = "insert-bucket";
8402         break;
8403
8404     case OFPGC15_REMOVE_BUCKET:
8405         cmd_str = "remove-bucket";
8406         break;
8407
8408     default:
8409         OVS_NOT_REACHED();
8410     }
8411
8412     ovs_fatal(0, "%s needs OpenFlow %s or later (\'-O OpenFlow%s\')",
8413               cmd_str, version, opt_version);
8414
8415 }
8416
8417 /* Converts abstract group mod 'gm' into a message for OpenFlow version
8418  * 'ofp_version' and returns the message. */
8419 struct ofpbuf *
8420 ofputil_encode_group_mod(enum ofp_version ofp_version,
8421                          const struct ofputil_group_mod *gm)
8422 {
8423
8424     switch (ofp_version) {
8425     case OFP10_VERSION:
8426         bad_group_cmd(gm->command);
8427
8428     case OFP11_VERSION:
8429     case OFP12_VERSION:
8430     case OFP13_VERSION:
8431     case OFP14_VERSION:
8432         if (gm->command > OFPGC11_DELETE) {
8433             bad_group_cmd(gm->command);
8434         }
8435         return ofputil_encode_ofp11_group_mod(ofp_version, gm);
8436
8437     case OFP15_VERSION:
8438         return ofputil_encode_ofp15_group_mod(ofp_version, gm);
8439
8440     default:
8441         OVS_NOT_REACHED();
8442     }
8443 }
8444
8445 static enum ofperr
8446 ofputil_pull_ofp11_group_mod(struct ofpbuf *msg, enum ofp_version ofp_version,
8447                              struct ofputil_group_mod *gm)
8448 {
8449     const struct ofp11_group_mod *ogm;
8450     enum ofperr error;
8451
8452     ogm = ofpbuf_pull(msg, sizeof *ogm);
8453     gm->command = ntohs(ogm->command);
8454     gm->type = ogm->type;
8455     gm->group_id = ntohl(ogm->group_id);
8456     gm->command_bucket_id = OFPG15_BUCKET_ALL;
8457
8458     error = ofputil_pull_ofp11_buckets(msg, msg->size, ofp_version,
8459                                        &gm->buckets);
8460
8461     /* OF1.3.5+ prescribes an error when an OFPGC_DELETE includes buckets. */
8462     if (!error
8463         && ofp_version >= OFP13_VERSION
8464         && gm->command == OFPGC11_DELETE
8465         && !list_is_empty(&gm->buckets)) {
8466         error = OFPERR_OFPGMFC_INVALID_GROUP;
8467     }
8468
8469     return error;
8470 }
8471
8472 static enum ofperr
8473 ofputil_pull_ofp15_group_mod(struct ofpbuf *msg, enum ofp_version ofp_version,
8474                              struct ofputil_group_mod *gm)
8475 {
8476     const struct ofp15_group_mod *ogm;
8477     uint16_t bucket_list_len;
8478     enum ofperr error = OFPERR_OFPGMFC_BAD_BUCKET;
8479
8480     ogm = ofpbuf_pull(msg, sizeof *ogm);
8481     gm->command = ntohs(ogm->command);
8482     gm->type = ogm->type;
8483     gm->group_id = ntohl(ogm->group_id);
8484
8485     gm->command_bucket_id = ntohl(ogm->command_bucket_id);
8486     switch (gm->command) {
8487     case OFPGC15_REMOVE_BUCKET:
8488         if (gm->command_bucket_id == OFPG15_BUCKET_ALL) {
8489             error = 0;
8490         }
8491         /* Fall through */
8492     case OFPGC15_INSERT_BUCKET:
8493         if (gm->command_bucket_id <= OFPG15_BUCKET_MAX ||
8494             gm->command_bucket_id == OFPG15_BUCKET_FIRST
8495             || gm->command_bucket_id == OFPG15_BUCKET_LAST) {
8496             error = 0;
8497         }
8498         break;
8499
8500     case OFPGC11_ADD:
8501     case OFPGC11_MODIFY:
8502     case OFPGC11_DELETE:
8503     default:
8504         if (gm->command_bucket_id == OFPG15_BUCKET_ALL) {
8505             error = 0;
8506         }
8507         break;
8508     }
8509     if (error) {
8510         VLOG_WARN_RL(&bad_ofmsg_rl,
8511                      "group command bucket id (%u) is out of range",
8512                      gm->command_bucket_id);
8513         return OFPERR_OFPGMFC_BAD_BUCKET;
8514     }
8515
8516     bucket_list_len = ntohs(ogm->bucket_array_len);
8517     error = ofputil_pull_ofp15_buckets(msg, bucket_list_len, ofp_version,
8518                                        gm->type, &gm->buckets);
8519     if (error) {
8520         return error;
8521     }
8522
8523     return parse_ofp15_group_properties(msg, gm->type, gm->command, &gm->props,
8524                                         msg->size);
8525 }
8526
8527 /* Converts OpenFlow group mod message 'oh' into an abstract group mod in
8528  * 'gm'.  Returns 0 if successful, otherwise an OpenFlow error code. */
8529 enum ofperr
8530 ofputil_decode_group_mod(const struct ofp_header *oh,
8531                          struct ofputil_group_mod *gm)
8532 {
8533     enum ofp_version ofp_version = oh->version;
8534     struct ofpbuf msg;
8535     struct ofputil_bucket *bucket;
8536     enum ofperr err;
8537
8538     ofpbuf_use_const(&msg, oh, ntohs(oh->length));
8539     ofpraw_pull_assert(&msg);
8540
8541     ofputil_init_group_properties(&gm->props);
8542
8543     switch (ofp_version)
8544     {
8545     case OFP11_VERSION:
8546     case OFP12_VERSION:
8547     case OFP13_VERSION:
8548     case OFP14_VERSION:
8549         err = ofputil_pull_ofp11_group_mod(&msg, ofp_version, gm);
8550         break;
8551
8552     case OFP15_VERSION:
8553         err = ofputil_pull_ofp15_group_mod(&msg, ofp_version, gm);
8554         break;
8555
8556     case OFP10_VERSION:
8557     default:
8558         OVS_NOT_REACHED();
8559     }
8560
8561     if (err) {
8562         return err;
8563     }
8564
8565     switch (gm->type) {
8566     case OFPGT11_INDIRECT:
8567         if (!list_is_singleton(&gm->buckets)) {
8568             return OFPERR_OFPGMFC_OUT_OF_BUCKETS;
8569         }
8570         break;
8571     case OFPGT11_ALL:
8572     case OFPGT11_SELECT:
8573     case OFPGT11_FF:
8574         break;
8575     default:
8576         OVS_NOT_REACHED();
8577     }
8578
8579     switch (gm->command) {
8580     case OFPGC11_ADD:
8581     case OFPGC11_MODIFY:
8582     case OFPGC11_DELETE:
8583     case OFPGC15_INSERT_BUCKET:
8584         break;
8585     case OFPGC15_REMOVE_BUCKET:
8586         if (!list_is_empty(&gm->buckets)) {
8587             return OFPERR_OFPGMFC_BAD_BUCKET;
8588         }
8589         break;
8590     default:
8591         OVS_NOT_REACHED();
8592     }
8593
8594     LIST_FOR_EACH (bucket, list_node, &gm->buckets) {
8595         if (bucket->weight && gm->type != OFPGT11_SELECT) {
8596             return OFPERR_OFPGMFC_INVALID_GROUP;
8597         }
8598
8599         switch (gm->type) {
8600         case OFPGT11_ALL:
8601         case OFPGT11_INDIRECT:
8602             if (ofputil_bucket_has_liveness(bucket)) {
8603                 return OFPERR_OFPGMFC_WATCH_UNSUPPORTED;
8604             }
8605             break;
8606         case OFPGT11_SELECT:
8607             break;
8608         case OFPGT11_FF:
8609             if (!ofputil_bucket_has_liveness(bucket)) {
8610                 return OFPERR_OFPGMFC_INVALID_GROUP;
8611             }
8612             break;
8613         default:
8614             OVS_NOT_REACHED();
8615         }
8616     }
8617
8618     return 0;
8619 }
8620
8621 /* Parse a queue status request message into 'oqsr'.
8622  * Returns 0 if successful, otherwise an OFPERR_* number. */
8623 enum ofperr
8624 ofputil_decode_queue_stats_request(const struct ofp_header *request,
8625                                    struct ofputil_queue_stats_request *oqsr)
8626 {
8627     switch ((enum ofp_version)request->version) {
8628     case OFP15_VERSION:
8629     case OFP14_VERSION:
8630     case OFP13_VERSION:
8631     case OFP12_VERSION:
8632     case OFP11_VERSION: {
8633         const struct ofp11_queue_stats_request *qsr11 = ofpmsg_body(request);
8634         oqsr->queue_id = ntohl(qsr11->queue_id);
8635         return ofputil_port_from_ofp11(qsr11->port_no, &oqsr->port_no);
8636     }
8637
8638     case OFP10_VERSION: {
8639         const struct ofp10_queue_stats_request *qsr10 = ofpmsg_body(request);
8640         oqsr->queue_id = ntohl(qsr10->queue_id);
8641         oqsr->port_no = u16_to_ofp(ntohs(qsr10->port_no));
8642         /* OF 1.0 uses OFPP_ALL for OFPP_ANY */
8643         if (oqsr->port_no == OFPP_ALL) {
8644             oqsr->port_no = OFPP_ANY;
8645         }
8646         return 0;
8647     }
8648
8649     default:
8650         OVS_NOT_REACHED();
8651     }
8652 }
8653
8654 /* Encode a queue stats request for 'oqsr', the encoded message
8655  * will be for OpenFlow version 'ofp_version'. Returns message
8656  * as a struct ofpbuf. Returns encoded message on success, NULL on error. */
8657 struct ofpbuf *
8658 ofputil_encode_queue_stats_request(enum ofp_version ofp_version,
8659                                    const struct ofputil_queue_stats_request *oqsr)
8660 {
8661     struct ofpbuf *request;
8662
8663     switch (ofp_version) {
8664     case OFP11_VERSION:
8665     case OFP12_VERSION:
8666     case OFP13_VERSION:
8667     case OFP14_VERSION:
8668     case OFP15_VERSION: {
8669         struct ofp11_queue_stats_request *req;
8670         request = ofpraw_alloc(OFPRAW_OFPST11_QUEUE_REQUEST, ofp_version, 0);
8671         req = ofpbuf_put_zeros(request, sizeof *req);
8672         req->port_no = ofputil_port_to_ofp11(oqsr->port_no);
8673         req->queue_id = htonl(oqsr->queue_id);
8674         break;
8675     }
8676     case OFP10_VERSION: {
8677         struct ofp10_queue_stats_request *req;
8678         request = ofpraw_alloc(OFPRAW_OFPST10_QUEUE_REQUEST, ofp_version, 0);
8679         req = ofpbuf_put_zeros(request, sizeof *req);
8680         /* OpenFlow 1.0 needs OFPP_ALL instead of OFPP_ANY */
8681         req->port_no = htons(ofp_to_u16(oqsr->port_no == OFPP_ANY
8682                                         ? OFPP_ALL : oqsr->port_no));
8683         req->queue_id = htonl(oqsr->queue_id);
8684         break;
8685     }
8686     default:
8687         OVS_NOT_REACHED();
8688     }
8689
8690     return request;
8691 }
8692
8693 /* Returns the number of queue stats elements in OFPTYPE_QUEUE_STATS_REPLY
8694  * message 'oh'. */
8695 size_t
8696 ofputil_count_queue_stats(const struct ofp_header *oh)
8697 {
8698     struct ofputil_queue_stats qs;
8699     struct ofpbuf b;
8700     size_t n = 0;
8701
8702     ofpbuf_use_const(&b, oh, ntohs(oh->length));
8703     ofpraw_pull_assert(&b);
8704     while (!ofputil_decode_queue_stats(&qs, &b)) {
8705         n++;
8706     }
8707     return n;
8708 }
8709
8710 static enum ofperr
8711 ofputil_queue_stats_from_ofp10(struct ofputil_queue_stats *oqs,
8712                                const struct ofp10_queue_stats *qs10)
8713 {
8714     oqs->port_no = u16_to_ofp(ntohs(qs10->port_no));
8715     oqs->queue_id = ntohl(qs10->queue_id);
8716     oqs->tx_bytes = ntohll(get_32aligned_be64(&qs10->tx_bytes));
8717     oqs->tx_packets = ntohll(get_32aligned_be64(&qs10->tx_packets));
8718     oqs->tx_errors = ntohll(get_32aligned_be64(&qs10->tx_errors));
8719     oqs->duration_sec = oqs->duration_nsec = UINT32_MAX;
8720
8721     return 0;
8722 }
8723
8724 static enum ofperr
8725 ofputil_queue_stats_from_ofp11(struct ofputil_queue_stats *oqs,
8726                                const struct ofp11_queue_stats *qs11)
8727 {
8728     enum ofperr error;
8729
8730     error = ofputil_port_from_ofp11(qs11->port_no, &oqs->port_no);
8731     if (error) {
8732         return error;
8733     }
8734
8735     oqs->queue_id = ntohl(qs11->queue_id);
8736     oqs->tx_bytes = ntohll(qs11->tx_bytes);
8737     oqs->tx_packets = ntohll(qs11->tx_packets);
8738     oqs->tx_errors = ntohll(qs11->tx_errors);
8739     oqs->duration_sec = oqs->duration_nsec = UINT32_MAX;
8740
8741     return 0;
8742 }
8743
8744 static enum ofperr
8745 ofputil_queue_stats_from_ofp13(struct ofputil_queue_stats *oqs,
8746                                const struct ofp13_queue_stats *qs13)
8747 {
8748     enum ofperr error = ofputil_queue_stats_from_ofp11(oqs, &qs13->qs);
8749     if (!error) {
8750         oqs->duration_sec = ntohl(qs13->duration_sec);
8751         oqs->duration_nsec = ntohl(qs13->duration_nsec);
8752     }
8753
8754     return error;
8755 }
8756
8757 static enum ofperr
8758 ofputil_pull_ofp14_queue_stats(struct ofputil_queue_stats *oqs,
8759                                struct ofpbuf *msg)
8760 {
8761     const struct ofp14_queue_stats *qs14;
8762     size_t len;
8763
8764     qs14 = ofpbuf_try_pull(msg, sizeof *qs14);
8765     if (!qs14) {
8766         return OFPERR_OFPBRC_BAD_LEN;
8767     }
8768
8769     len = ntohs(qs14->length);
8770     if (len < sizeof *qs14 || len - sizeof *qs14 > msg->size) {
8771         return OFPERR_OFPBRC_BAD_LEN;
8772     }
8773     ofpbuf_pull(msg, len - sizeof *qs14);
8774
8775     /* No properties yet defined, so ignore them for now. */
8776
8777     return ofputil_queue_stats_from_ofp13(oqs, &qs14->qs);
8778 }
8779
8780 /* Converts an OFPST_QUEUE_STATS reply in 'msg' into an abstract
8781  * ofputil_queue_stats in 'qs'.
8782  *
8783  * Multiple OFPST_QUEUE_STATS replies can be packed into a single OpenFlow
8784  * message.  Calling this function multiple times for a single 'msg' iterates
8785  * through the replies.  The caller must initially leave 'msg''s layer pointers
8786  * null and not modify them between calls.
8787  *
8788  * Returns 0 if successful, EOF if no replies were left in this 'msg',
8789  * otherwise a positive errno value. */
8790 int
8791 ofputil_decode_queue_stats(struct ofputil_queue_stats *qs, struct ofpbuf *msg)
8792 {
8793     enum ofperr error;
8794     enum ofpraw raw;
8795
8796     error = (msg->header ? ofpraw_decode(&raw, msg->header)
8797              : ofpraw_pull(&raw, msg));
8798     if (error) {
8799         return error;
8800     }
8801
8802     if (!msg->size) {
8803         return EOF;
8804     } else if (raw == OFPRAW_OFPST14_QUEUE_REPLY) {
8805         return ofputil_pull_ofp14_queue_stats(qs, msg);
8806     } else if (raw == OFPRAW_OFPST13_QUEUE_REPLY) {
8807         const struct ofp13_queue_stats *qs13;
8808
8809         qs13 = ofpbuf_try_pull(msg, sizeof *qs13);
8810         if (!qs13) {
8811             goto bad_len;
8812         }
8813         return ofputil_queue_stats_from_ofp13(qs, qs13);
8814     } else if (raw == OFPRAW_OFPST11_QUEUE_REPLY) {
8815         const struct ofp11_queue_stats *qs11;
8816
8817         qs11 = ofpbuf_try_pull(msg, sizeof *qs11);
8818         if (!qs11) {
8819             goto bad_len;
8820         }
8821         return ofputil_queue_stats_from_ofp11(qs, qs11);
8822     } else if (raw == OFPRAW_OFPST10_QUEUE_REPLY) {
8823         const struct ofp10_queue_stats *qs10;
8824
8825         qs10 = ofpbuf_try_pull(msg, sizeof *qs10);
8826         if (!qs10) {
8827             goto bad_len;
8828         }
8829         return ofputil_queue_stats_from_ofp10(qs, qs10);
8830     } else {
8831         OVS_NOT_REACHED();
8832     }
8833
8834  bad_len:
8835     VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_QUEUE reply has %"PRIu32" leftover "
8836                  "bytes at end", msg->size);
8837     return OFPERR_OFPBRC_BAD_LEN;
8838 }
8839
8840 static void
8841 ofputil_queue_stats_to_ofp10(const struct ofputil_queue_stats *oqs,
8842                              struct ofp10_queue_stats *qs10)
8843 {
8844     qs10->port_no = htons(ofp_to_u16(oqs->port_no));
8845     memset(qs10->pad, 0, sizeof qs10->pad);
8846     qs10->queue_id = htonl(oqs->queue_id);
8847     put_32aligned_be64(&qs10->tx_bytes, htonll(oqs->tx_bytes));
8848     put_32aligned_be64(&qs10->tx_packets, htonll(oqs->tx_packets));
8849     put_32aligned_be64(&qs10->tx_errors, htonll(oqs->tx_errors));
8850 }
8851
8852 static void
8853 ofputil_queue_stats_to_ofp11(const struct ofputil_queue_stats *oqs,
8854                              struct ofp11_queue_stats *qs11)
8855 {
8856     qs11->port_no = ofputil_port_to_ofp11(oqs->port_no);
8857     qs11->queue_id = htonl(oqs->queue_id);
8858     qs11->tx_bytes = htonll(oqs->tx_bytes);
8859     qs11->tx_packets = htonll(oqs->tx_packets);
8860     qs11->tx_errors = htonll(oqs->tx_errors);
8861 }
8862
8863 static void
8864 ofputil_queue_stats_to_ofp13(const struct ofputil_queue_stats *oqs,
8865                              struct ofp13_queue_stats *qs13)
8866 {
8867     ofputil_queue_stats_to_ofp11(oqs, &qs13->qs);
8868     if (oqs->duration_sec != UINT32_MAX) {
8869         qs13->duration_sec = htonl(oqs->duration_sec);
8870         qs13->duration_nsec = htonl(oqs->duration_nsec);
8871     } else {
8872         qs13->duration_sec = OVS_BE32_MAX;
8873         qs13->duration_nsec = OVS_BE32_MAX;
8874     }
8875 }
8876
8877 static void
8878 ofputil_queue_stats_to_ofp14(const struct ofputil_queue_stats *oqs,
8879                              struct ofp14_queue_stats *qs14)
8880 {
8881     qs14->length = htons(sizeof *qs14);
8882     memset(qs14->pad, 0, sizeof qs14->pad);
8883     ofputil_queue_stats_to_ofp13(oqs, &qs14->qs);
8884 }
8885
8886
8887 /* Encode a queue stat for 'oqs' and append it to 'replies'. */
8888 void
8889 ofputil_append_queue_stat(struct ovs_list *replies,
8890                           const struct ofputil_queue_stats *oqs)
8891 {
8892     switch (ofpmp_version(replies)) {
8893     case OFP13_VERSION: {
8894         struct ofp13_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
8895         ofputil_queue_stats_to_ofp13(oqs, reply);
8896         break;
8897     }
8898
8899     case OFP12_VERSION:
8900     case OFP11_VERSION: {
8901         struct ofp11_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
8902         ofputil_queue_stats_to_ofp11(oqs, reply);
8903         break;
8904     }
8905
8906     case OFP10_VERSION: {
8907         struct ofp10_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
8908         ofputil_queue_stats_to_ofp10(oqs, reply);
8909         break;
8910     }
8911
8912     case OFP14_VERSION:
8913     case OFP15_VERSION: {
8914         struct ofp14_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
8915         ofputil_queue_stats_to_ofp14(oqs, reply);
8916         break;
8917     }
8918
8919     default:
8920         OVS_NOT_REACHED();
8921     }
8922 }
8923
8924 enum ofperr
8925 ofputil_decode_bundle_ctrl(const struct ofp_header *oh,
8926                            struct ofputil_bundle_ctrl_msg *msg)
8927 {
8928     struct ofpbuf b;
8929     enum ofpraw raw;
8930     const struct ofp14_bundle_ctrl_msg *m;
8931
8932     ofpbuf_use_const(&b, oh, ntohs(oh->length));
8933     raw = ofpraw_pull_assert(&b);
8934     ovs_assert(raw == OFPRAW_OFPT14_BUNDLE_CONTROL);
8935
8936     m = b.msg;
8937     msg->bundle_id = ntohl(m->bundle_id);
8938     msg->type = ntohs(m->type);
8939     msg->flags = ntohs(m->flags);
8940
8941     return 0;
8942 }
8943
8944 struct ofpbuf *
8945 ofputil_encode_bundle_ctrl_request(enum ofp_version ofp_version,
8946                                    struct ofputil_bundle_ctrl_msg *bc)
8947 {
8948     struct ofpbuf *request;
8949     struct ofp14_bundle_ctrl_msg *m;
8950
8951     switch (ofp_version) {
8952     case OFP10_VERSION:
8953     case OFP11_VERSION:
8954     case OFP12_VERSION:
8955     case OFP13_VERSION:
8956         ovs_fatal(0, "bundles need OpenFlow 1.4 or later "
8957                      "(\'-O OpenFlow14\')");
8958     case OFP14_VERSION:
8959     case OFP15_VERSION:
8960         request = ofpraw_alloc(OFPRAW_OFPT14_BUNDLE_CONTROL, ofp_version, 0);
8961         m = ofpbuf_put_zeros(request, sizeof *m);
8962
8963         m->bundle_id = htonl(bc->bundle_id);
8964         m->type = htons(bc->type);
8965         m->flags = htons(bc->flags);
8966         break;
8967     default:
8968         OVS_NOT_REACHED();
8969     }
8970
8971     return request;
8972 }
8973
8974 struct ofpbuf *
8975 ofputil_encode_bundle_ctrl_reply(const struct ofp_header *oh,
8976                                  struct ofputil_bundle_ctrl_msg *msg)
8977 {
8978     struct ofpbuf *buf;
8979     struct ofp14_bundle_ctrl_msg *m;
8980
8981     buf = ofpraw_alloc_reply(OFPRAW_OFPT14_BUNDLE_CONTROL, oh, 0);
8982     m = ofpbuf_put_zeros(buf, sizeof *m);
8983
8984     m->bundle_id = htonl(msg->bundle_id);
8985     m->type = htons(msg->type);
8986     m->flags = htons(msg->flags);
8987
8988     return buf;
8989 }
8990
8991 /* Return true for bundlable state change requests, false for other messages.
8992  */
8993 static bool
8994 ofputil_is_bundlable(enum ofptype type)
8995 {
8996     switch (type) {
8997         /* Minimum required by OpenFlow 1.4. */
8998     case OFPTYPE_PORT_MOD:
8999     case OFPTYPE_FLOW_MOD:
9000         return true;
9001
9002         /* Nice to have later. */
9003     case OFPTYPE_FLOW_MOD_TABLE_ID:
9004     case OFPTYPE_GROUP_MOD:
9005     case OFPTYPE_TABLE_MOD:
9006     case OFPTYPE_METER_MOD:
9007     case OFPTYPE_PACKET_OUT:
9008     case OFPTYPE_NXT_GENEVE_TABLE_MOD:
9009
9010         /* Not to be bundlable. */
9011     case OFPTYPE_ECHO_REQUEST:
9012     case OFPTYPE_FEATURES_REQUEST:
9013     case OFPTYPE_GET_CONFIG_REQUEST:
9014     case OFPTYPE_SET_CONFIG:
9015     case OFPTYPE_BARRIER_REQUEST:
9016     case OFPTYPE_ROLE_REQUEST:
9017     case OFPTYPE_ECHO_REPLY:
9018     case OFPTYPE_SET_FLOW_FORMAT:
9019     case OFPTYPE_SET_PACKET_IN_FORMAT:
9020     case OFPTYPE_SET_CONTROLLER_ID:
9021     case OFPTYPE_FLOW_AGE:
9022     case OFPTYPE_FLOW_MONITOR_CANCEL:
9023     case OFPTYPE_SET_ASYNC_CONFIG:
9024     case OFPTYPE_GET_ASYNC_REQUEST:
9025     case OFPTYPE_DESC_STATS_REQUEST:
9026     case OFPTYPE_FLOW_STATS_REQUEST:
9027     case OFPTYPE_AGGREGATE_STATS_REQUEST:
9028     case OFPTYPE_TABLE_STATS_REQUEST:
9029     case OFPTYPE_TABLE_FEATURES_STATS_REQUEST:
9030     case OFPTYPE_TABLE_DESC_REQUEST:
9031     case OFPTYPE_PORT_STATS_REQUEST:
9032     case OFPTYPE_QUEUE_STATS_REQUEST:
9033     case OFPTYPE_PORT_DESC_STATS_REQUEST:
9034     case OFPTYPE_FLOW_MONITOR_STATS_REQUEST:
9035     case OFPTYPE_METER_STATS_REQUEST:
9036     case OFPTYPE_METER_CONFIG_STATS_REQUEST:
9037     case OFPTYPE_METER_FEATURES_STATS_REQUEST:
9038     case OFPTYPE_GROUP_STATS_REQUEST:
9039     case OFPTYPE_GROUP_DESC_STATS_REQUEST:
9040     case OFPTYPE_GROUP_FEATURES_STATS_REQUEST:
9041     case OFPTYPE_QUEUE_GET_CONFIG_REQUEST:
9042     case OFPTYPE_BUNDLE_CONTROL:
9043     case OFPTYPE_BUNDLE_ADD_MESSAGE:
9044     case OFPTYPE_HELLO:
9045     case OFPTYPE_ERROR:
9046     case OFPTYPE_FEATURES_REPLY:
9047     case OFPTYPE_GET_CONFIG_REPLY:
9048     case OFPTYPE_PACKET_IN:
9049     case OFPTYPE_FLOW_REMOVED:
9050     case OFPTYPE_PORT_STATUS:
9051     case OFPTYPE_BARRIER_REPLY:
9052     case OFPTYPE_QUEUE_GET_CONFIG_REPLY:
9053     case OFPTYPE_DESC_STATS_REPLY:
9054     case OFPTYPE_FLOW_STATS_REPLY:
9055     case OFPTYPE_QUEUE_STATS_REPLY:
9056     case OFPTYPE_PORT_STATS_REPLY:
9057     case OFPTYPE_TABLE_STATS_REPLY:
9058     case OFPTYPE_AGGREGATE_STATS_REPLY:
9059     case OFPTYPE_PORT_DESC_STATS_REPLY:
9060     case OFPTYPE_ROLE_REPLY:
9061     case OFPTYPE_FLOW_MONITOR_PAUSED:
9062     case OFPTYPE_FLOW_MONITOR_RESUMED:
9063     case OFPTYPE_FLOW_MONITOR_STATS_REPLY:
9064     case OFPTYPE_GET_ASYNC_REPLY:
9065     case OFPTYPE_GROUP_STATS_REPLY:
9066     case OFPTYPE_GROUP_DESC_STATS_REPLY:
9067     case OFPTYPE_GROUP_FEATURES_STATS_REPLY:
9068     case OFPTYPE_METER_STATS_REPLY:
9069     case OFPTYPE_METER_CONFIG_STATS_REPLY:
9070     case OFPTYPE_METER_FEATURES_STATS_REPLY:
9071     case OFPTYPE_TABLE_FEATURES_STATS_REPLY:
9072     case OFPTYPE_TABLE_DESC_REPLY:
9073     case OFPTYPE_ROLE_STATUS:
9074     case OFPTYPE_NXT_GENEVE_TABLE_REQUEST:
9075     case OFPTYPE_NXT_GENEVE_TABLE_REPLY:
9076         break;
9077     }
9078
9079     return false;
9080 }
9081
9082 enum ofperr
9083 ofputil_decode_bundle_add(const struct ofp_header *oh,
9084                           struct ofputil_bundle_add_msg *msg,
9085                           enum ofptype *type_ptr)
9086 {
9087     const struct ofp14_bundle_ctrl_msg *m;
9088     struct ofpbuf b;
9089     enum ofpraw raw;
9090     size_t inner_len;
9091     enum ofperr error;
9092     enum ofptype type;
9093
9094     ofpbuf_use_const(&b, oh, ntohs(oh->length));
9095     raw = ofpraw_pull_assert(&b);
9096     ovs_assert(raw == OFPRAW_OFPT14_BUNDLE_ADD_MESSAGE);
9097
9098     m = ofpbuf_pull(&b, sizeof *m);
9099     msg->bundle_id = ntohl(m->bundle_id);
9100     msg->flags = ntohs(m->flags);
9101
9102     msg->msg = b.data;
9103     if (msg->msg->version != oh->version) {
9104         return OFPERR_NXBFC_BAD_VERSION;
9105     }
9106     inner_len = ntohs(msg->msg->length);
9107     if (inner_len < sizeof(struct ofp_header) || inner_len > b.size) {
9108         return OFPERR_OFPBFC_MSG_BAD_LEN;
9109     }
9110     if (msg->msg->xid != oh->xid) {
9111         return OFPERR_OFPBFC_MSG_BAD_XID;
9112     }
9113
9114     /* Reject unbundlable messages. */
9115     if (!type_ptr) {
9116         type_ptr = &type;
9117     }
9118     error = ofptype_decode(type_ptr, msg->msg);
9119     if (error) {
9120         VLOG_WARN_RL(&bad_ofmsg_rl, "OFPT14_BUNDLE_ADD_MESSAGE contained "
9121                      "message is unparsable (%s)", ofperr_get_name(error));
9122         return OFPERR_OFPBFC_MSG_UNSUP; /* 'error' would be confusing. */
9123     }
9124
9125     if (!ofputil_is_bundlable(*type_ptr)) {
9126         VLOG_WARN_RL(&bad_ofmsg_rl, "%s message not allowed inside "
9127                      "OFPT14_BUNDLE_ADD_MESSAGE", ofptype_get_name(*type_ptr));
9128         return OFPERR_OFPBFC_MSG_UNSUP;
9129     }
9130
9131     return 0;
9132 }
9133
9134 struct ofpbuf *
9135 ofputil_encode_bundle_add(enum ofp_version ofp_version,
9136                           struct ofputil_bundle_add_msg *msg)
9137 {
9138     struct ofpbuf *request;
9139     struct ofp14_bundle_ctrl_msg *m;
9140
9141     /* Must use the same xid as the embedded message. */
9142     request = ofpraw_alloc_xid(OFPRAW_OFPT14_BUNDLE_ADD_MESSAGE, ofp_version,
9143                                msg->msg->xid, 0);
9144     m = ofpbuf_put_zeros(request, sizeof *m);
9145
9146     m->bundle_id = htonl(msg->bundle_id);
9147     m->flags = htons(msg->flags);
9148     ofpbuf_put(request, msg->msg, ntohs(msg->msg->length));
9149
9150     return request;
9151 }
9152
9153 static void
9154 encode_geneve_table_mappings(struct ofpbuf *b, struct ovs_list *mappings)
9155 {
9156     struct ofputil_geneve_map *map;
9157
9158     LIST_FOR_EACH (map, list_node, mappings) {
9159         struct nx_geneve_map *nx_map;
9160
9161         nx_map = ofpbuf_put_zeros(b, sizeof *nx_map);
9162         nx_map->option_class = htons(map->option_class);
9163         nx_map->option_type = map->option_type;
9164         nx_map->option_len = map->option_len;
9165         nx_map->index = htons(map->index);
9166     }
9167 }
9168
9169 struct ofpbuf *
9170 ofputil_encode_geneve_table_mod(enum ofp_version ofp_version,
9171                                 struct ofputil_geneve_table_mod *gtm)
9172 {
9173     struct ofpbuf *b;
9174     struct nx_geneve_table_mod *nx_gtm;
9175
9176     b = ofpraw_alloc(OFPRAW_NXT_GENEVE_TABLE_MOD, ofp_version, 0);
9177     nx_gtm = ofpbuf_put_zeros(b, sizeof *nx_gtm);
9178     nx_gtm->command = htons(gtm->command);
9179     encode_geneve_table_mappings(b, &gtm->mappings);
9180
9181     return b;
9182 }
9183
9184 static enum ofperr
9185 decode_geneve_table_mappings(struct ofpbuf *msg, unsigned int max_fields,
9186                              struct ovs_list *mappings)
9187 {
9188     list_init(mappings);
9189
9190     while (msg->size) {
9191         struct nx_geneve_map *nx_map;
9192         struct ofputil_geneve_map *map;
9193
9194         nx_map = ofpbuf_pull(msg, sizeof *nx_map);
9195         map = xmalloc(sizeof *map);
9196         list_push_back(mappings, &map->list_node);
9197
9198         map->option_class = ntohs(nx_map->option_class);
9199         map->option_type = nx_map->option_type;
9200
9201         map->option_len = nx_map->option_len;
9202         if (map->option_len == 0 || map->option_len % 4 ||
9203             map->option_len > GENEVE_MAX_OPT_SIZE) {
9204             VLOG_WARN_RL(&bad_ofmsg_rl,
9205                          "geneve table option length (%u) is not a valid option size",
9206                          map->option_len);
9207             ofputil_uninit_geneve_table(mappings);
9208             return OFPERR_NXGTMFC_BAD_OPT_LEN;
9209         }
9210
9211         map->index = ntohs(nx_map->index);
9212         if (map->index >= max_fields) {
9213             VLOG_WARN_RL(&bad_ofmsg_rl,
9214                          "geneve table field index (%u) is too large (max %u)",
9215                          map->index, max_fields - 1);
9216             ofputil_uninit_geneve_table(mappings);
9217             return OFPERR_NXGTMFC_BAD_FIELD_IDX;
9218         }
9219     }
9220
9221     return 0;
9222 }
9223
9224 enum ofperr
9225 ofputil_decode_geneve_table_mod(const struct ofp_header *oh,
9226                                 struct ofputil_geneve_table_mod *gtm)
9227 {
9228     struct ofpbuf msg;
9229     struct nx_geneve_table_mod *nx_gtm;
9230
9231     ofpbuf_use_const(&msg, oh, ntohs(oh->length));
9232     ofpraw_pull_assert(&msg);
9233
9234     nx_gtm = ofpbuf_pull(&msg, sizeof *nx_gtm);
9235     gtm->command = ntohs(nx_gtm->command);
9236     if (gtm->command > NXGTMC_CLEAR) {
9237         VLOG_WARN_RL(&bad_ofmsg_rl,
9238                      "geneve table mod command (%u) is out of range",
9239                      gtm->command);
9240         return OFPERR_NXGTMFC_BAD_COMMAND;
9241     }
9242
9243     return decode_geneve_table_mappings(&msg, TUN_METADATA_NUM_OPTS,
9244                                         &gtm->mappings);
9245 }
9246
9247 struct ofpbuf *
9248 ofputil_encode_geneve_table_reply(const struct ofp_header *oh,
9249                                   struct ofputil_geneve_table_reply *gtr)
9250 {
9251     struct ofpbuf *b;
9252     struct nx_geneve_table_reply *nx_gtr;
9253
9254     b = ofpraw_alloc_reply(OFPRAW_NXT_GENEVE_TABLE_REPLY, oh, 0);
9255     nx_gtr = ofpbuf_put_zeros(b, sizeof *nx_gtr);
9256     nx_gtr->max_option_space = htonl(gtr->max_option_space);
9257     nx_gtr->max_fields = htons(gtr->max_fields);
9258
9259     encode_geneve_table_mappings(b, &gtr->mappings);
9260
9261     return b;
9262 }
9263
9264 /* Decodes the NXT_GENEVE_TABLE_REPLY message in 'oh' into '*gtr'.  Returns 0
9265  * if successful, otherwise an ofperr.
9266  *
9267  * The decoder verifies that the indexes in 'gtr->mappings' are less than
9268  * 'gtr->max_fields', but the caller must ensure, if necessary, that they are
9269  * less than TUN_METADATA_NUM_OPTS. */
9270 enum ofperr
9271 ofputil_decode_geneve_table_reply(const struct ofp_header *oh,
9272                                   struct ofputil_geneve_table_reply *gtr)
9273 {
9274     struct ofpbuf msg;
9275     struct nx_geneve_table_reply *nx_gtr;
9276
9277     ofpbuf_use_const(&msg, oh, ntohs(oh->length));
9278     ofpraw_pull_assert(&msg);
9279
9280     nx_gtr = ofpbuf_pull(&msg, sizeof *nx_gtr);
9281     gtr->max_option_space = ntohl(nx_gtr->max_option_space);
9282     gtr->max_fields = ntohs(nx_gtr->max_fields);
9283
9284     return decode_geneve_table_mappings(&msg, gtr->max_fields, &gtr->mappings);
9285 }
9286
9287 void
9288 ofputil_uninit_geneve_table(struct ovs_list *mappings)
9289 {
9290     struct ofputil_geneve_map *map;
9291
9292     LIST_FOR_EACH_POP (map, list_node, mappings) {
9293         free(map);
9294     }
9295 }
9296
9297 /* Decodes the OpenFlow "set async config" request and "get async config
9298  * reply" message in '*oh' into an abstract form in 'master' and 'slave'.
9299  *
9300  * If 'loose' is true, this function ignores properties and values that it does
9301  * not understand, as a controller would want to do when interpreting
9302  * capabilities provided by a switch.  If 'loose' is false, this function
9303  * treats unknown properties and values as an error, as a switch would want to
9304  * do when interpreting a configuration request made by a controller.
9305  *
9306  * Returns 0 if successful, otherwise an OFPERR_* value. */
9307 enum ofperr
9308 ofputil_decode_set_async_config(const struct ofp_header *oh,
9309                                 uint32_t master[OAM_N_TYPES],
9310                                 uint32_t slave[OAM_N_TYPES],
9311                                 bool loose)
9312 {
9313     enum ofpraw raw;
9314     struct ofpbuf b;
9315
9316     ofpbuf_use_const(&b, oh, ntohs(oh->length));
9317     raw = ofpraw_pull_assert(&b);
9318
9319     if (raw == OFPRAW_OFPT13_SET_ASYNC ||
9320         raw == OFPRAW_NXT_SET_ASYNC_CONFIG ||
9321         raw == OFPRAW_OFPT13_GET_ASYNC_REPLY) {
9322         const struct nx_async_config *msg = ofpmsg_body(oh);
9323
9324         master[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[0]);
9325         master[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[0]);
9326         master[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[0]);
9327
9328         slave[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[1]);
9329         slave[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[1]);
9330         slave[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[1]);
9331
9332     } else if (raw == OFPRAW_OFPT14_SET_ASYNC ||
9333                raw == OFPRAW_OFPT14_GET_ASYNC_REPLY) {
9334
9335         while (b.size > 0) {
9336             struct ofp14_async_config_prop_reasons *msg;
9337             struct ofpbuf property;
9338             enum ofperr error;
9339             uint16_t type;
9340
9341             error = ofputil_pull_property(&b, &property, &type);
9342             if (error) {
9343                 return error;
9344             }
9345
9346             msg = property.data;
9347
9348             if (property.size != sizeof *msg) {
9349                 return OFPERR_OFPBRC_BAD_LEN;
9350             }
9351
9352             switch (type) {
9353             case OFPACPT_PACKET_IN_SLAVE:
9354                 slave[OAM_PACKET_IN] = ntohl(msg->mask);
9355                 break;
9356
9357             case OFPACPT_PACKET_IN_MASTER:
9358                 master[OAM_PACKET_IN] = ntohl(msg->mask);
9359                 break;
9360
9361             case OFPACPT_PORT_STATUS_SLAVE:
9362                 slave[OAM_PORT_STATUS] = ntohl(msg->mask);
9363                 break;
9364
9365             case OFPACPT_PORT_STATUS_MASTER:
9366                 master[OAM_PORT_STATUS] = ntohl(msg->mask);
9367                 break;
9368
9369             case OFPACPT_FLOW_REMOVED_SLAVE:
9370                 slave[OAM_FLOW_REMOVED] = ntohl(msg->mask);
9371                 break;
9372
9373             case OFPACPT_FLOW_REMOVED_MASTER:
9374                 master[OAM_FLOW_REMOVED] = ntohl(msg->mask);
9375                 break;
9376
9377             case OFPACPT_ROLE_STATUS_SLAVE:
9378                 slave[OAM_ROLE_STATUS] = ntohl(msg->mask);
9379                 break;
9380
9381             case OFPACPT_ROLE_STATUS_MASTER:
9382                 master[OAM_ROLE_STATUS] = ntohl(msg->mask);
9383                 break;
9384
9385             case OFPACPT_TABLE_STATUS_SLAVE:
9386                 slave[OAM_TABLE_STATUS] = ntohl(msg->mask);
9387                 break;
9388
9389             case OFPACPT_TABLE_STATUS_MASTER:
9390                 master[OAM_TABLE_STATUS] = ntohl(msg->mask);
9391                 break;
9392
9393             case OFPACPT_REQUESTFORWARD_SLAVE:
9394                 slave[OAM_REQUESTFORWARD] = ntohl(msg->mask);
9395                 break;
9396
9397             case OFPACPT_REQUESTFORWARD_MASTER:
9398                 master[OAM_REQUESTFORWARD] = ntohl(msg->mask);
9399                 break;
9400
9401             default:
9402                 error = loose ? 0 : OFPERR_OFPBPC_BAD_TYPE;
9403                 break;
9404             }
9405             if (error) {
9406                 return error;
9407             }
9408         }
9409     } else {
9410         return OFPERR_OFPBRC_BAD_VERSION;
9411     }
9412     return 0;
9413 }
9414
9415 /* Append all asynchronous configuration properties in GET_ASYNC_REPLY
9416  * message, describing if various set of asynchronous messages are enabled
9417  * or not. */
9418 static enum ofperr
9419 ofputil_get_async_reply(struct ofpbuf *buf, const uint32_t master_mask,
9420                         const uint32_t slave_mask, const uint32_t type)
9421 {
9422     int role;
9423
9424     for (role = 0; role < 2; role++) {
9425         struct ofp14_async_config_prop_reasons *msg;
9426
9427         msg = ofpbuf_put_zeros(buf, sizeof *msg);
9428
9429         switch (type) {
9430         case OAM_PACKET_IN:
9431             msg->type = (role ? htons(OFPACPT_PACKET_IN_SLAVE)
9432                               : htons(OFPACPT_PACKET_IN_MASTER));
9433             break;
9434
9435         case OAM_PORT_STATUS:
9436             msg->type = (role ? htons(OFPACPT_PORT_STATUS_SLAVE)
9437                               : htons(OFPACPT_PORT_STATUS_MASTER));
9438             break;
9439
9440         case OAM_FLOW_REMOVED:
9441             msg->type = (role ? htons(OFPACPT_FLOW_REMOVED_SLAVE)
9442                               : htons(OFPACPT_FLOW_REMOVED_MASTER));
9443             break;
9444
9445         case OAM_ROLE_STATUS:
9446             msg->type = (role ? htons(OFPACPT_ROLE_STATUS_SLAVE)
9447                               : htons(OFPACPT_ROLE_STATUS_MASTER));
9448             break;
9449
9450         case OAM_TABLE_STATUS:
9451             msg->type = (role ? htons(OFPACPT_TABLE_STATUS_SLAVE)
9452                               : htons(OFPACPT_TABLE_STATUS_MASTER));
9453             break;
9454
9455         case OAM_REQUESTFORWARD:
9456             msg->type = (role ? htons(OFPACPT_REQUESTFORWARD_SLAVE)
9457                               : htons(OFPACPT_REQUESTFORWARD_MASTER));
9458             break;
9459
9460         default:
9461             return OFPERR_OFPBRC_BAD_TYPE;
9462         }
9463         msg->length = htons(sizeof *msg);
9464         msg->mask = (role ? htonl(slave_mask) : htonl(master_mask));
9465     }
9466
9467     return 0;
9468 }
9469
9470 /* Returns a OpenFlow message that encodes 'asynchronous configuration' properly
9471  * as a reply to get async config request. */
9472 struct ofpbuf *
9473 ofputil_encode_get_async_config(const struct ofp_header *oh,
9474                                 uint32_t master[OAM_N_TYPES],
9475                                 uint32_t slave[OAM_N_TYPES])
9476 {
9477     struct ofpbuf *buf;
9478     uint32_t type;
9479
9480     buf = ofpraw_alloc_reply((oh->version < OFP14_VERSION
9481                               ? OFPRAW_OFPT13_GET_ASYNC_REPLY
9482                               : OFPRAW_OFPT14_GET_ASYNC_REPLY), oh, 0);
9483
9484     if (oh->version < OFP14_VERSION) {
9485         struct nx_async_config *msg;
9486         msg = ofpbuf_put_zeros(buf, sizeof *msg);
9487
9488         msg->packet_in_mask[0] = htonl(master[OAM_PACKET_IN]);
9489         msg->port_status_mask[0] = htonl(master[OAM_PORT_STATUS]);
9490         msg->flow_removed_mask[0] = htonl(master[OAM_FLOW_REMOVED]);
9491
9492         msg->packet_in_mask[1] = htonl(slave[OAM_PACKET_IN]);
9493         msg->port_status_mask[1] = htonl(slave[OAM_PORT_STATUS]);
9494         msg->flow_removed_mask[1] = htonl(slave[OAM_FLOW_REMOVED]);
9495     } else if (oh->version == OFP14_VERSION) {
9496         for (type = 0; type < OAM_N_TYPES; type++) {
9497             ofputil_get_async_reply(buf, master[type], slave[type], type);
9498         }
9499     }
9500
9501     return buf;
9502 }