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