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