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