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