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