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