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