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