Add skeleton for OF1.5 support.
[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 void
3932 ofputil_append_port_desc_stats_reply(const struct ofputil_phy_port *pp,
3933                                      struct list *replies)
3934 {
3935     struct ofpbuf *reply = ofpbuf_from_list(list_back(replies));
3936     size_t start_ofs = ofpbuf_size(reply);
3937
3938     ofputil_put_phy_port(ofpmp_version(replies), pp, reply);
3939     ofpmp_postappend(replies, start_ofs);
3940 }
3941 \f
3942 /* ofputil_switch_features */
3943
3944 #define OFPC_COMMON (OFPC_FLOW_STATS | OFPC_TABLE_STATS | OFPC_PORT_STATS | \
3945                      OFPC_IP_REASM | OFPC_QUEUE_STATS)
3946 BUILD_ASSERT_DECL((int) OFPUTIL_C_FLOW_STATS == OFPC_FLOW_STATS);
3947 BUILD_ASSERT_DECL((int) OFPUTIL_C_TABLE_STATS == OFPC_TABLE_STATS);
3948 BUILD_ASSERT_DECL((int) OFPUTIL_C_PORT_STATS == OFPC_PORT_STATS);
3949 BUILD_ASSERT_DECL((int) OFPUTIL_C_IP_REASM == OFPC_IP_REASM);
3950 BUILD_ASSERT_DECL((int) OFPUTIL_C_QUEUE_STATS == OFPC_QUEUE_STATS);
3951 BUILD_ASSERT_DECL((int) OFPUTIL_C_ARP_MATCH_IP == OFPC_ARP_MATCH_IP);
3952
3953 struct ofputil_action_bit_translation {
3954     enum ofputil_action_bitmap ofputil_bit;
3955     int of_bit;
3956 };
3957
3958 static const struct ofputil_action_bit_translation of10_action_bits[] = {
3959     { OFPUTIL_A_OUTPUT,       OFPAT10_OUTPUT },
3960     { OFPUTIL_A_SET_VLAN_VID, OFPAT10_SET_VLAN_VID },
3961     { OFPUTIL_A_SET_VLAN_PCP, OFPAT10_SET_VLAN_PCP },
3962     { OFPUTIL_A_STRIP_VLAN,   OFPAT10_STRIP_VLAN },
3963     { OFPUTIL_A_SET_DL_SRC,   OFPAT10_SET_DL_SRC },
3964     { OFPUTIL_A_SET_DL_DST,   OFPAT10_SET_DL_DST },
3965     { OFPUTIL_A_SET_NW_SRC,   OFPAT10_SET_NW_SRC },
3966     { OFPUTIL_A_SET_NW_DST,   OFPAT10_SET_NW_DST },
3967     { OFPUTIL_A_SET_NW_TOS,   OFPAT10_SET_NW_TOS },
3968     { OFPUTIL_A_SET_TP_SRC,   OFPAT10_SET_TP_SRC },
3969     { OFPUTIL_A_SET_TP_DST,   OFPAT10_SET_TP_DST },
3970     { OFPUTIL_A_ENQUEUE,      OFPAT10_ENQUEUE },
3971     { 0, 0 },
3972 };
3973
3974 static enum ofputil_action_bitmap
3975 decode_action_bits(ovs_be32 of_actions,
3976                    const struct ofputil_action_bit_translation *x)
3977 {
3978     enum ofputil_action_bitmap ofputil_actions;
3979
3980     ofputil_actions = 0;
3981     for (; x->ofputil_bit; x++) {
3982         if (of_actions & htonl(1u << x->of_bit)) {
3983             ofputil_actions |= x->ofputil_bit;
3984         }
3985     }
3986     return ofputil_actions;
3987 }
3988
3989 static uint32_t
3990 ofputil_capabilities_mask(enum ofp_version ofp_version)
3991 {
3992     /* Handle capabilities whose bit is unique for all Open Flow versions */
3993     switch (ofp_version) {
3994     case OFP10_VERSION:
3995     case OFP11_VERSION:
3996         return OFPC_COMMON | OFPC_ARP_MATCH_IP;
3997     case OFP12_VERSION:
3998     case OFP13_VERSION:
3999     case OFP14_VERSION:
4000     case OFP15_VERSION:
4001         return OFPC_COMMON | OFPC12_PORT_BLOCKED;
4002     default:
4003         /* Caller needs to check osf->header.version itself */
4004         return 0;
4005     }
4006 }
4007
4008 /* Decodes an OpenFlow 1.0 or 1.1 "switch_features" structure 'osf' into an
4009  * abstract representation in '*features'.  Initializes '*b' to iterate over
4010  * the OpenFlow port structures following 'osf' with later calls to
4011  * ofputil_pull_phy_port().  Returns 0 if successful, otherwise an
4012  * OFPERR_* value.  */
4013 enum ofperr
4014 ofputil_decode_switch_features(const struct ofp_header *oh,
4015                                struct ofputil_switch_features *features,
4016                                struct ofpbuf *b)
4017 {
4018     const struct ofp_switch_features *osf;
4019     enum ofpraw raw;
4020
4021     ofpbuf_use_const(b, oh, ntohs(oh->length));
4022     raw = ofpraw_pull_assert(b);
4023
4024     osf = ofpbuf_pull(b, sizeof *osf);
4025     features->datapath_id = ntohll(osf->datapath_id);
4026     features->n_buffers = ntohl(osf->n_buffers);
4027     features->n_tables = osf->n_tables;
4028     features->auxiliary_id = 0;
4029
4030     features->capabilities = ntohl(osf->capabilities) &
4031         ofputil_capabilities_mask(oh->version);
4032
4033     if (raw == OFPRAW_OFPT10_FEATURES_REPLY) {
4034         if (osf->capabilities & htonl(OFPC10_STP)) {
4035             features->capabilities |= OFPUTIL_C_STP;
4036         }
4037         features->actions = decode_action_bits(osf->actions, of10_action_bits);
4038     } else if (raw == OFPRAW_OFPT11_FEATURES_REPLY
4039                || raw == OFPRAW_OFPT13_FEATURES_REPLY) {
4040         if (osf->capabilities & htonl(OFPC11_GROUP_STATS)) {
4041             features->capabilities |= OFPUTIL_C_GROUP_STATS;
4042         }
4043         features->actions = 0;
4044         if (raw == OFPRAW_OFPT13_FEATURES_REPLY) {
4045             features->auxiliary_id = osf->auxiliary_id;
4046         }
4047     } else {
4048         return OFPERR_OFPBRC_BAD_VERSION;
4049     }
4050
4051     return 0;
4052 }
4053
4054 /* In OpenFlow 1.0, 1.1, and 1.2, an OFPT_FEATURES_REPLY message lists all the
4055  * switch's ports, unless there are too many to fit.  In OpenFlow 1.3 and
4056  * later, an OFPT_FEATURES_REPLY does not list ports at all.
4057  *
4058  * Given a buffer 'b' that contains a Features Reply message, this message
4059  * checks if it contains a complete list of the switch's ports.  Returns true,
4060  * if so.  Returns false if the list is missing (OF1.3+) or incomplete
4061  * (OF1.0/1.1/1.2), and in the latter case removes all of the ports from the
4062  * message.
4063  *
4064  * When this function returns false, the caller should send an OFPST_PORT_DESC
4065  * stats request to get the ports. */
4066 bool
4067 ofputil_switch_features_has_ports(struct ofpbuf *b)
4068 {
4069     struct ofp_header *oh = ofpbuf_data(b);
4070     size_t phy_port_size;
4071
4072     if (oh->version >= OFP13_VERSION) {
4073         /* OpenFlow 1.3+ never has ports in the feature reply. */
4074         return false;
4075     }
4076
4077     phy_port_size = (oh->version == OFP10_VERSION
4078                      ? sizeof(struct ofp10_phy_port)
4079                      : sizeof(struct ofp11_port));
4080     if (ntohs(oh->length) + phy_port_size <= UINT16_MAX) {
4081         /* There's room for additional ports in the feature reply.
4082          * Assume that the list is complete. */
4083         return true;
4084     }
4085
4086     /* The feature reply has no room for more ports.  Probably the list is
4087      * truncated.  Drop the ports and tell the caller to retrieve them with
4088      * OFPST_PORT_DESC. */
4089     ofpbuf_set_size(b, sizeof *oh + sizeof(struct ofp_switch_features));
4090     ofpmsg_update_length(b);
4091     return false;
4092 }
4093
4094 static ovs_be32
4095 encode_action_bits(enum ofputil_action_bitmap ofputil_actions,
4096                    const struct ofputil_action_bit_translation *x)
4097 {
4098     uint32_t of_actions;
4099
4100     of_actions = 0;
4101     for (; x->ofputil_bit; x++) {
4102         if (ofputil_actions & x->ofputil_bit) {
4103             of_actions |= 1 << x->of_bit;
4104         }
4105     }
4106     return htonl(of_actions);
4107 }
4108
4109 /* Returns a buffer owned by the caller that encodes 'features' in the format
4110  * required by 'protocol' with the given 'xid'.  The caller should append port
4111  * information to the buffer with subsequent calls to
4112  * ofputil_put_switch_features_port(). */
4113 struct ofpbuf *
4114 ofputil_encode_switch_features(const struct ofputil_switch_features *features,
4115                                enum ofputil_protocol protocol, ovs_be32 xid)
4116 {
4117     struct ofp_switch_features *osf;
4118     struct ofpbuf *b;
4119     enum ofp_version version;
4120     enum ofpraw raw;
4121
4122     version = ofputil_protocol_to_ofp_version(protocol);
4123     switch (version) {
4124     case OFP10_VERSION:
4125         raw = OFPRAW_OFPT10_FEATURES_REPLY;
4126         break;
4127     case OFP11_VERSION:
4128     case OFP12_VERSION:
4129         raw = OFPRAW_OFPT11_FEATURES_REPLY;
4130         break;
4131     case OFP13_VERSION:
4132     case OFP14_VERSION:
4133     case OFP15_VERSION:
4134         raw = OFPRAW_OFPT13_FEATURES_REPLY;
4135         break;
4136     default:
4137         OVS_NOT_REACHED();
4138     }
4139     b = ofpraw_alloc_xid(raw, version, xid, 0);
4140     osf = ofpbuf_put_zeros(b, sizeof *osf);
4141     osf->datapath_id = htonll(features->datapath_id);
4142     osf->n_buffers = htonl(features->n_buffers);
4143     osf->n_tables = features->n_tables;
4144
4145     osf->capabilities = htonl(features->capabilities & OFPC_COMMON);
4146     osf->capabilities = htonl(features->capabilities &
4147                               ofputil_capabilities_mask(version));
4148     switch (version) {
4149     case OFP10_VERSION:
4150         if (features->capabilities & OFPUTIL_C_STP) {
4151             osf->capabilities |= htonl(OFPC10_STP);
4152         }
4153         osf->actions = encode_action_bits(features->actions, of10_action_bits);
4154         break;
4155     case OFP13_VERSION:
4156     case OFP14_VERSION:
4157     case OFP15_VERSION:
4158         osf->auxiliary_id = features->auxiliary_id;
4159         /* fall through */
4160     case OFP11_VERSION:
4161     case OFP12_VERSION:
4162         if (features->capabilities & OFPUTIL_C_GROUP_STATS) {
4163             osf->capabilities |= htonl(OFPC11_GROUP_STATS);
4164         }
4165         break;
4166     default:
4167         OVS_NOT_REACHED();
4168     }
4169
4170     return b;
4171 }
4172
4173 /* Encodes 'pp' into the format required by the switch_features message already
4174  * in 'b', which should have been returned by ofputil_encode_switch_features(),
4175  * and appends the encoded version to 'b'. */
4176 void
4177 ofputil_put_switch_features_port(const struct ofputil_phy_port *pp,
4178                                  struct ofpbuf *b)
4179 {
4180     const struct ofp_header *oh = ofpbuf_data(b);
4181
4182     if (oh->version < OFP13_VERSION) {
4183         /* Try adding a port description to the message, but drop it again if
4184          * the buffer overflows.  (This possibility for overflow is why
4185          * OpenFlow 1.3+ moved port descriptions into a multipart message.)  */
4186         size_t start_ofs = ofpbuf_size(b);
4187         ofputil_put_phy_port(oh->version, pp, b);
4188         if (ofpbuf_size(b) > UINT16_MAX) {
4189             ofpbuf_set_size(b, start_ofs);
4190         }
4191     }
4192 }
4193 \f
4194 /* ofputil_port_status */
4195
4196 /* Decodes the OpenFlow "port status" message in '*ops' into an abstract form
4197  * in '*ps'.  Returns 0 if successful, otherwise an OFPERR_* value. */
4198 enum ofperr
4199 ofputil_decode_port_status(const struct ofp_header *oh,
4200                            struct ofputil_port_status *ps)
4201 {
4202     const struct ofp_port_status *ops;
4203     struct ofpbuf b;
4204     int retval;
4205
4206     ofpbuf_use_const(&b, oh, ntohs(oh->length));
4207     ofpraw_pull_assert(&b);
4208     ops = ofpbuf_pull(&b, sizeof *ops);
4209
4210     if (ops->reason != OFPPR_ADD &&
4211         ops->reason != OFPPR_DELETE &&
4212         ops->reason != OFPPR_MODIFY) {
4213         return OFPERR_NXBRC_BAD_REASON;
4214     }
4215     ps->reason = ops->reason;
4216
4217     retval = ofputil_pull_phy_port(oh->version, &b, &ps->desc);
4218     ovs_assert(retval != EOF);
4219     return retval;
4220 }
4221
4222 /* Converts the abstract form of a "port status" message in '*ps' into an
4223  * OpenFlow message suitable for 'protocol', and returns that encoded form in
4224  * a buffer owned by the caller. */
4225 struct ofpbuf *
4226 ofputil_encode_port_status(const struct ofputil_port_status *ps,
4227                            enum ofputil_protocol protocol)
4228 {
4229     struct ofp_port_status *ops;
4230     struct ofpbuf *b;
4231     enum ofp_version version;
4232     enum ofpraw raw;
4233
4234     version = ofputil_protocol_to_ofp_version(protocol);
4235     switch (version) {
4236     case OFP10_VERSION:
4237         raw = OFPRAW_OFPT10_PORT_STATUS;
4238         break;
4239
4240     case OFP11_VERSION:
4241     case OFP12_VERSION:
4242     case OFP13_VERSION:
4243         raw = OFPRAW_OFPT11_PORT_STATUS;
4244         break;
4245
4246     case OFP14_VERSION:
4247     case OFP15_VERSION:
4248         raw = OFPRAW_OFPT14_PORT_STATUS;
4249         break;
4250
4251     default:
4252         OVS_NOT_REACHED();
4253     }
4254
4255     b = ofpraw_alloc_xid(raw, version, htonl(0), 0);
4256     ops = ofpbuf_put_zeros(b, sizeof *ops);
4257     ops->reason = ps->reason;
4258     ofputil_put_phy_port(version, &ps->desc, b);
4259     ofpmsg_update_length(b);
4260     return b;
4261 }
4262
4263 /* ofputil_port_mod */
4264
4265 static enum ofperr
4266 parse_port_mod_ethernet_property(struct ofpbuf *property,
4267                                  struct ofputil_port_mod *pm)
4268 {
4269     struct ofp14_port_mod_prop_ethernet *eth = ofpbuf_data(property);
4270
4271     if (ofpbuf_size(property) != sizeof *eth) {
4272         return OFPERR_OFPBRC_BAD_LEN;
4273     }
4274
4275     pm->advertise = netdev_port_features_from_ofp11(eth->advertise);
4276     return 0;
4277 }
4278
4279 /* Decodes the OpenFlow "port mod" message in '*oh' into an abstract form in
4280  * '*pm'.  Returns 0 if successful, otherwise an OFPERR_* value. */
4281 enum ofperr
4282 ofputil_decode_port_mod(const struct ofp_header *oh,
4283                         struct ofputil_port_mod *pm, bool loose)
4284 {
4285     enum ofpraw raw;
4286     struct ofpbuf b;
4287
4288     ofpbuf_use_const(&b, oh, ntohs(oh->length));
4289     raw = ofpraw_pull_assert(&b);
4290
4291     if (raw == OFPRAW_OFPT10_PORT_MOD) {
4292         const struct ofp10_port_mod *opm = ofpbuf_data(&b);
4293
4294         pm->port_no = u16_to_ofp(ntohs(opm->port_no));
4295         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
4296         pm->config = ntohl(opm->config) & OFPPC10_ALL;
4297         pm->mask = ntohl(opm->mask) & OFPPC10_ALL;
4298         pm->advertise = netdev_port_features_from_ofp10(opm->advertise);
4299     } else if (raw == OFPRAW_OFPT11_PORT_MOD) {
4300         const struct ofp11_port_mod *opm = ofpbuf_data(&b);
4301         enum ofperr error;
4302
4303         error = ofputil_port_from_ofp11(opm->port_no, &pm->port_no);
4304         if (error) {
4305             return error;
4306         }
4307
4308         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
4309         pm->config = ntohl(opm->config) & OFPPC11_ALL;
4310         pm->mask = ntohl(opm->mask) & OFPPC11_ALL;
4311         pm->advertise = netdev_port_features_from_ofp11(opm->advertise);
4312     } else if (raw == OFPRAW_OFPT14_PORT_MOD) {
4313         const struct ofp14_port_mod *opm = ofpbuf_pull(&b, sizeof *opm);
4314         enum ofperr error;
4315
4316         memset(pm, 0, sizeof *pm);
4317
4318         error = ofputil_port_from_ofp11(opm->port_no, &pm->port_no);
4319         if (error) {
4320             return error;
4321         }
4322
4323         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
4324         pm->config = ntohl(opm->config) & OFPPC11_ALL;
4325         pm->mask = ntohl(opm->mask) & OFPPC11_ALL;
4326
4327         while (ofpbuf_size(&b) > 0) {
4328             struct ofpbuf property;
4329             enum ofperr error;
4330             uint16_t type;
4331
4332             error = ofputil_pull_property(&b, &property, &type);
4333             if (error) {
4334                 return error;
4335             }
4336
4337             switch (type) {
4338             case OFPPMPT14_ETHERNET:
4339                 error = parse_port_mod_ethernet_property(&property, pm);
4340                 break;
4341
4342             default:
4343                 log_property(loose, "unknown port_mod property %"PRIu16, type);
4344                 if (loose) {
4345                     error = 0;
4346                 } else if (type == OFPPMPT14_EXPERIMENTER) {
4347                     error = OFPERR_OFPBPC_BAD_EXPERIMENTER;
4348                 } else {
4349                     error = OFPERR_OFPBRC_BAD_TYPE;
4350                 }
4351                 break;
4352             }
4353
4354             if (error) {
4355                 return error;
4356             }
4357         }
4358     } else {
4359         return OFPERR_OFPBRC_BAD_TYPE;
4360     }
4361
4362     pm->config &= pm->mask;
4363     return 0;
4364 }
4365
4366 /* Converts the abstract form of a "port mod" message in '*pm' into an OpenFlow
4367  * message suitable for 'protocol', and returns that encoded form in a buffer
4368  * owned by the caller. */
4369 struct ofpbuf *
4370 ofputil_encode_port_mod(const struct ofputil_port_mod *pm,
4371                         enum ofputil_protocol protocol)
4372 {
4373     enum ofp_version ofp_version = ofputil_protocol_to_ofp_version(protocol);
4374     struct ofpbuf *b;
4375
4376     switch (ofp_version) {
4377     case OFP10_VERSION: {
4378         struct ofp10_port_mod *opm;
4379
4380         b = ofpraw_alloc(OFPRAW_OFPT10_PORT_MOD, ofp_version, 0);
4381         opm = ofpbuf_put_zeros(b, sizeof *opm);
4382         opm->port_no = htons(ofp_to_u16(pm->port_no));
4383         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
4384         opm->config = htonl(pm->config & OFPPC10_ALL);
4385         opm->mask = htonl(pm->mask & OFPPC10_ALL);
4386         opm->advertise = netdev_port_features_to_ofp10(pm->advertise);
4387         break;
4388     }
4389
4390     case OFP11_VERSION:
4391     case OFP12_VERSION:
4392     case OFP13_VERSION: {
4393         struct ofp11_port_mod *opm;
4394
4395         b = ofpraw_alloc(OFPRAW_OFPT11_PORT_MOD, ofp_version, 0);
4396         opm = ofpbuf_put_zeros(b, sizeof *opm);
4397         opm->port_no = ofputil_port_to_ofp11(pm->port_no);
4398         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
4399         opm->config = htonl(pm->config & OFPPC11_ALL);
4400         opm->mask = htonl(pm->mask & OFPPC11_ALL);
4401         opm->advertise = netdev_port_features_to_ofp11(pm->advertise);
4402         break;
4403     }
4404     case OFP14_VERSION:
4405     case OFP15_VERSION: {
4406         struct ofp14_port_mod_prop_ethernet *eth;
4407         struct ofp14_port_mod *opm;
4408
4409         b = ofpraw_alloc(OFPRAW_OFPT14_PORT_MOD, ofp_version, sizeof *eth);
4410         opm = ofpbuf_put_zeros(b, sizeof *opm);
4411         opm->port_no = ofputil_port_to_ofp11(pm->port_no);
4412         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
4413         opm->config = htonl(pm->config & OFPPC11_ALL);
4414         opm->mask = htonl(pm->mask & OFPPC11_ALL);
4415
4416         if (pm->advertise) {
4417             eth = ofpbuf_put_zeros(b, sizeof *eth);
4418             eth->type = htons(OFPPMPT14_ETHERNET);
4419             eth->length = htons(sizeof *eth);
4420             eth->advertise = netdev_port_features_to_ofp11(pm->advertise);
4421         }
4422         break;
4423     }
4424     default:
4425         OVS_NOT_REACHED();
4426     }
4427
4428     return b;
4429 }
4430
4431 static enum ofperr
4432 pull_table_feature_property(struct ofpbuf *msg, struct ofpbuf *payload,
4433                         uint16_t *typep)
4434 {
4435     enum ofperr error;
4436
4437     error = ofputil_pull_property(msg, payload, typep);
4438     if (payload && !error) {
4439         ofpbuf_pull(payload, sizeof(struct ofp_prop_header));
4440     }
4441     return error;
4442 }
4443
4444 static enum ofperr
4445 parse_table_ids(struct ofpbuf *payload, uint32_t *ids)
4446 {
4447     uint16_t type;
4448
4449     *ids = 0;
4450     while (ofpbuf_size(payload) > 0) {
4451         enum ofperr error = pull_table_feature_property(payload, NULL, &type);
4452         if (error) {
4453             return error;
4454         }
4455         if (type < CHAR_BIT * sizeof *ids) {
4456             *ids |= 1u << type;
4457         }
4458     }
4459     return 0;
4460 }
4461
4462 static enum ofperr
4463 parse_instruction_ids(struct ofpbuf *payload, bool loose, uint32_t *insts)
4464 {
4465     *insts = 0;
4466     while (ofpbuf_size(payload) > 0) {
4467         enum ovs_instruction_type inst;
4468         enum ofperr error;
4469         uint16_t ofpit;
4470
4471         error = pull_table_feature_property(payload, NULL, &ofpit);
4472         if (error) {
4473             return error;
4474         }
4475
4476         error = ovs_instruction_type_from_inst_type(&inst, ofpit);
4477         if (!error) {
4478             *insts |= 1u << inst;
4479         } else if (!loose) {
4480             return error;
4481         }
4482     }
4483     return 0;
4484 }
4485
4486 static enum ofperr
4487 parse_table_features_next_table(struct ofpbuf *payload,
4488                                 unsigned long int *next_tables)
4489 {
4490     size_t i;
4491
4492     memset(next_tables, 0, bitmap_n_bytes(255));
4493     for (i = 0; i < ofpbuf_size(payload); i++) {
4494         uint8_t id = ((const uint8_t *) ofpbuf_data(payload))[i];
4495         if (id >= 255) {
4496             return OFPERR_OFPBPC_BAD_VALUE;
4497         }
4498         bitmap_set1(next_tables, id);
4499     }
4500     return 0;
4501 }
4502
4503 static enum ofperr
4504 parse_oxm(struct ofpbuf *b, bool loose,
4505           const struct mf_field **fieldp, bool *hasmask)
4506 {
4507     ovs_be32 *oxmp;
4508     uint32_t oxm;
4509
4510     oxmp = ofpbuf_try_pull(b, sizeof *oxmp);
4511     if (!oxmp) {
4512         return OFPERR_OFPBPC_BAD_LEN;
4513     }
4514     oxm = ntohl(*oxmp);
4515
4516     /* Determine '*hasmask'.  If 'oxm' is masked, convert it to the equivalent
4517      * unmasked version, because the table of OXM fields we support only has
4518      * masked versions of fields that we support with masks, but we should be
4519      * able to parse the masked versions of those here. */
4520     *hasmask = NXM_HASMASK(oxm);
4521     if (*hasmask) {
4522         if (NXM_LENGTH(oxm) & 1) {
4523             return OFPERR_OFPBPC_BAD_VALUE;
4524         }
4525         oxm = NXM_HEADER(NXM_VENDOR(oxm), NXM_FIELD(oxm), NXM_LENGTH(oxm) / 2);
4526     }
4527
4528     *fieldp = mf_from_nxm_header(oxm);
4529     if (!*fieldp) {
4530         log_property(loose, "unknown OXM field %#"PRIx32, ntohl(*oxmp));
4531     }
4532     return *fieldp ? 0 : OFPERR_OFPBMC_BAD_FIELD;
4533 }
4534
4535 static enum ofperr
4536 parse_oxms(struct ofpbuf *payload, bool loose,
4537            uint64_t *exactp, uint64_t *maskedp)
4538 {
4539     uint64_t exact, masked;
4540
4541     exact = masked = 0;
4542     while (ofpbuf_size(payload) > 0) {
4543         const struct mf_field *field;
4544         enum ofperr error;
4545         bool hasmask;
4546
4547         error = parse_oxm(payload, loose, &field, &hasmask);
4548         if (!error) {
4549             if (hasmask) {
4550                 masked |= UINT64_C(1) << field->id;
4551             } else {
4552                 exact |= UINT64_C(1) << field->id;
4553             }
4554         } else if (error != OFPERR_OFPBMC_BAD_FIELD || !loose) {
4555             return error;
4556         }
4557     }
4558     if (exactp) {
4559         *exactp = exact;
4560     } else if (exact) {
4561         return OFPERR_OFPBMC_BAD_MASK;
4562     }
4563     if (maskedp) {
4564         *maskedp = masked;
4565     } else if (masked) {
4566         return OFPERR_OFPBMC_BAD_MASK;
4567     }
4568     return 0;
4569 }
4570
4571 /* Converts an OFPMP_TABLE_FEATURES request or reply in 'msg' into an abstract
4572  * ofputil_table_features in 'tf'.
4573  *
4574  * If 'loose' is true, this function ignores properties and values that it does
4575  * not understand, as a controller would want to do when interpreting
4576  * capabilities provided by a switch.  If 'loose' is false, this function
4577  * treats unknown properties and values as an error, as a switch would want to
4578  * do when interpreting a configuration request made by a controller.
4579  *
4580  * A single OpenFlow message can specify features for multiple tables.  Calling
4581  * this function multiple times for a single 'msg' iterates through the tables
4582  * in the message.  The caller must initially leave 'msg''s layer pointers null
4583  * and not modify them between calls.
4584  *
4585  * Returns 0 if successful, EOF if no tables were left in this 'msg', otherwise
4586  * a positive "enum ofperr" value. */
4587 int
4588 ofputil_decode_table_features(struct ofpbuf *msg,
4589                               struct ofputil_table_features *tf, bool loose)
4590 {
4591     struct ofp13_table_features *otf;
4592     unsigned int len;
4593
4594     if (!msg->frame) {
4595         ofpraw_pull_assert(msg);
4596     }
4597
4598     if (!ofpbuf_size(msg)) {
4599         return EOF;
4600     }
4601
4602     if (ofpbuf_size(msg) < sizeof *otf) {
4603         return OFPERR_OFPBPC_BAD_LEN;
4604     }
4605
4606     otf = ofpbuf_data(msg);
4607     len = ntohs(otf->length);
4608     if (len < sizeof *otf || len % 8 || len > ofpbuf_size(msg)) {
4609         return OFPERR_OFPBPC_BAD_LEN;
4610     }
4611     ofpbuf_pull(msg, sizeof *otf);
4612
4613     tf->table_id = otf->table_id;
4614     if (tf->table_id == OFPTT_ALL) {
4615         return OFPERR_OFPTFFC_BAD_TABLE;
4616     }
4617
4618     ovs_strlcpy(tf->name, otf->name, OFP_MAX_TABLE_NAME_LEN);
4619     tf->metadata_match = otf->metadata_match;
4620     tf->metadata_write = otf->metadata_write;
4621     tf->config = ntohl(otf->config);
4622     tf->max_entries = ntohl(otf->max_entries);
4623
4624     while (ofpbuf_size(msg) > 0) {
4625         struct ofpbuf payload;
4626         enum ofperr error;
4627         uint16_t type;
4628
4629         error = pull_table_feature_property(msg, &payload, &type);
4630         if (error) {
4631             return error;
4632         }
4633
4634         switch ((enum ofp13_table_feature_prop_type) type) {
4635         case OFPTFPT13_INSTRUCTIONS:
4636             error = parse_instruction_ids(&payload, loose,
4637                                           &tf->nonmiss.instructions);
4638             break;
4639         case OFPTFPT13_INSTRUCTIONS_MISS:
4640             error = parse_instruction_ids(&payload, loose,
4641                                           &tf->miss.instructions);
4642             break;
4643
4644         case OFPTFPT13_NEXT_TABLES:
4645             error = parse_table_features_next_table(&payload,
4646                                                     tf->nonmiss.next);
4647             break;
4648         case OFPTFPT13_NEXT_TABLES_MISS:
4649             error = parse_table_features_next_table(&payload, tf->miss.next);
4650             break;
4651
4652         case OFPTFPT13_WRITE_ACTIONS:
4653             error = parse_table_ids(&payload, &tf->nonmiss.write.actions);
4654             break;
4655         case OFPTFPT13_WRITE_ACTIONS_MISS:
4656             error = parse_table_ids(&payload, &tf->miss.write.actions);
4657             break;
4658
4659         case OFPTFPT13_APPLY_ACTIONS:
4660             error = parse_table_ids(&payload, &tf->nonmiss.apply.actions);
4661             break;
4662         case OFPTFPT13_APPLY_ACTIONS_MISS:
4663             error = parse_table_ids(&payload, &tf->miss.apply.actions);
4664             break;
4665
4666         case OFPTFPT13_MATCH:
4667             error = parse_oxms(&payload, loose, &tf->match, &tf->mask);
4668             break;
4669         case OFPTFPT13_WILDCARDS:
4670             error = parse_oxms(&payload, loose, &tf->wildcard, NULL);
4671             break;
4672
4673         case OFPTFPT13_WRITE_SETFIELD:
4674             error = parse_oxms(&payload, loose,
4675                                &tf->nonmiss.write.set_fields, NULL);
4676             break;
4677         case OFPTFPT13_WRITE_SETFIELD_MISS:
4678             error = parse_oxms(&payload, loose,
4679                                &tf->miss.write.set_fields, NULL);
4680             break;
4681         case OFPTFPT13_APPLY_SETFIELD:
4682             error = parse_oxms(&payload, loose,
4683                                &tf->nonmiss.apply.set_fields, NULL);
4684             break;
4685         case OFPTFPT13_APPLY_SETFIELD_MISS:
4686             error = parse_oxms(&payload, loose,
4687                                &tf->miss.apply.set_fields, NULL);
4688             break;
4689
4690         case OFPTFPT13_EXPERIMENTER:
4691         case OFPTFPT13_EXPERIMENTER_MISS:
4692         default:
4693             log_property(loose, "unknown table features property %"PRIu16,
4694                          type);
4695             error = loose ? 0 : OFPERR_OFPBPC_BAD_TYPE;
4696             break;
4697         }
4698         if (error) {
4699             return error;
4700         }
4701     }
4702
4703     /* Fix inconsistencies:
4704      *
4705      *     - Turn off 'mask' and 'wildcard' bits that are not in 'match',
4706      *       because a field must be matchable to be masked or wildcarded.
4707      *
4708      *     - Turn on 'wildcard' bits that are set in 'mask', because a field
4709      *       that is arbitrarily maskable can be wildcarded entirely. */
4710     tf->mask &= tf->match;
4711     tf->wildcard &= tf->match;
4712
4713     tf->wildcard |= tf->mask;
4714
4715     return 0;
4716 }
4717
4718 /* Encodes and returns a request to obtain the table features of a switch.
4719  * The message is encoded for OpenFlow version 'ofp_version'. */
4720 struct ofpbuf *
4721 ofputil_encode_table_features_request(enum ofp_version ofp_version)
4722 {
4723     struct ofpbuf *request = NULL;
4724
4725     switch (ofp_version) {
4726     case OFP10_VERSION:
4727     case OFP11_VERSION:
4728     case OFP12_VERSION:
4729         ovs_fatal(0, "dump-table-features needs OpenFlow 1.3 or later "
4730                      "(\'-O OpenFlow13\')");
4731     case OFP13_VERSION:
4732     case OFP14_VERSION:
4733     case OFP15_VERSION:
4734         request = ofpraw_alloc(OFPRAW_OFPST13_TABLE_FEATURES_REQUEST,
4735                                ofp_version, 0);
4736         break;
4737     default:
4738         OVS_NOT_REACHED();
4739     }
4740
4741     return request;
4742 }
4743
4744 /* ofputil_table_mod */
4745
4746 /* Decodes the OpenFlow "table mod" message in '*oh' into an abstract form in
4747  * '*pm'.  Returns 0 if successful, otherwise an OFPERR_* value. */
4748 enum ofperr
4749 ofputil_decode_table_mod(const struct ofp_header *oh,
4750                          struct ofputil_table_mod *pm)
4751 {
4752     enum ofpraw raw;
4753     struct ofpbuf b;
4754
4755     ofpbuf_use_const(&b, oh, ntohs(oh->length));
4756     raw = ofpraw_pull_assert(&b);
4757
4758     if (raw == OFPRAW_OFPT11_TABLE_MOD) {
4759         const struct ofp11_table_mod *otm = ofpbuf_data(&b);
4760
4761         pm->table_id = otm->table_id;
4762         pm->config = ntohl(otm->config);
4763     } else if (raw == OFPRAW_OFPT14_TABLE_MOD) {
4764         const struct ofp14_table_mod *otm = ofpbuf_pull(&b, sizeof *otm);
4765
4766         pm->table_id = otm->table_id;
4767         pm->config = ntohl(otm->config);
4768         /* We do not understand any properties yet, so we do not bother
4769          * parsing them. */
4770     } else {
4771         return OFPERR_OFPBRC_BAD_TYPE;
4772     }
4773
4774     return 0;
4775 }
4776
4777 /* Converts the abstract form of a "table mod" message in '*pm' into an OpenFlow
4778  * message suitable for 'protocol', and returns that encoded form in a buffer
4779  * owned by the caller. */
4780 struct ofpbuf *
4781 ofputil_encode_table_mod(const struct ofputil_table_mod *pm,
4782                         enum ofputil_protocol protocol)
4783 {
4784     enum ofp_version ofp_version = ofputil_protocol_to_ofp_version(protocol);
4785     struct ofpbuf *b;
4786
4787     switch (ofp_version) {
4788     case OFP10_VERSION: {
4789         ovs_fatal(0, "table mod needs OpenFlow 1.1 or later "
4790                      "(\'-O OpenFlow11\')");
4791         break;
4792     }
4793     case OFP11_VERSION:
4794     case OFP12_VERSION:
4795     case OFP13_VERSION: {
4796         struct ofp11_table_mod *otm;
4797
4798         b = ofpraw_alloc(OFPRAW_OFPT11_TABLE_MOD, ofp_version, 0);
4799         otm = ofpbuf_put_zeros(b, sizeof *otm);
4800         otm->table_id = pm->table_id;
4801         otm->config = htonl(pm->config);
4802         break;
4803     }
4804     case OFP14_VERSION:
4805     case OFP15_VERSION: {
4806         struct ofp14_table_mod *otm;
4807
4808         b = ofpraw_alloc(OFPRAW_OFPT14_TABLE_MOD, ofp_version, 0);
4809         otm = ofpbuf_put_zeros(b, sizeof *otm);
4810         otm->table_id = pm->table_id;
4811         otm->config = htonl(pm->config);
4812         break;
4813     }
4814     default:
4815         OVS_NOT_REACHED();
4816     }
4817
4818     return b;
4819 }
4820 \f
4821 /* ofputil_role_request */
4822
4823 /* Decodes the OpenFlow "role request" or "role reply" message in '*oh' into
4824  * an abstract form in '*rr'.  Returns 0 if successful, otherwise an
4825  * OFPERR_* value. */
4826 enum ofperr
4827 ofputil_decode_role_message(const struct ofp_header *oh,
4828                             struct ofputil_role_request *rr)
4829 {
4830     struct ofpbuf b;
4831     enum ofpraw raw;
4832
4833     ofpbuf_use_const(&b, oh, ntohs(oh->length));
4834     raw = ofpraw_pull_assert(&b);
4835
4836     if (raw == OFPRAW_OFPT12_ROLE_REQUEST ||
4837         raw == OFPRAW_OFPT12_ROLE_REPLY) {
4838         const struct ofp12_role_request *orr = ofpbuf_l3(&b);
4839
4840         if (orr->role != htonl(OFPCR12_ROLE_NOCHANGE) &&
4841             orr->role != htonl(OFPCR12_ROLE_EQUAL) &&
4842             orr->role != htonl(OFPCR12_ROLE_MASTER) &&
4843             orr->role != htonl(OFPCR12_ROLE_SLAVE)) {
4844             return OFPERR_OFPRRFC_BAD_ROLE;
4845         }
4846
4847         rr->role = ntohl(orr->role);
4848         if (raw == OFPRAW_OFPT12_ROLE_REQUEST
4849             ? orr->role == htonl(OFPCR12_ROLE_NOCHANGE)
4850             : orr->generation_id == OVS_BE64_MAX) {
4851             rr->have_generation_id = false;
4852             rr->generation_id = 0;
4853         } else {
4854             rr->have_generation_id = true;
4855             rr->generation_id = ntohll(orr->generation_id);
4856         }
4857     } else if (raw == OFPRAW_NXT_ROLE_REQUEST ||
4858                raw == OFPRAW_NXT_ROLE_REPLY) {
4859         const struct nx_role_request *nrr = ofpbuf_l3(&b);
4860
4861         BUILD_ASSERT(NX_ROLE_OTHER + 1 == OFPCR12_ROLE_EQUAL);
4862         BUILD_ASSERT(NX_ROLE_MASTER + 1 == OFPCR12_ROLE_MASTER);
4863         BUILD_ASSERT(NX_ROLE_SLAVE + 1 == OFPCR12_ROLE_SLAVE);
4864
4865         if (nrr->role != htonl(NX_ROLE_OTHER) &&
4866             nrr->role != htonl(NX_ROLE_MASTER) &&
4867             nrr->role != htonl(NX_ROLE_SLAVE)) {
4868             return OFPERR_OFPRRFC_BAD_ROLE;
4869         }
4870
4871         rr->role = ntohl(nrr->role) + 1;
4872         rr->have_generation_id = false;
4873         rr->generation_id = 0;
4874     } else {
4875         OVS_NOT_REACHED();
4876     }
4877
4878     return 0;
4879 }
4880
4881 /* Returns an encoded form of a role reply suitable for the "request" in a
4882  * buffer owned by the caller. */
4883 struct ofpbuf *
4884 ofputil_encode_role_reply(const struct ofp_header *request,
4885                           const struct ofputil_role_request *rr)
4886 {
4887     struct ofpbuf *buf;
4888     enum ofpraw raw;
4889
4890     raw = ofpraw_decode_assert(request);
4891     if (raw == OFPRAW_OFPT12_ROLE_REQUEST) {
4892         struct ofp12_role_request *orr;
4893
4894         buf = ofpraw_alloc_reply(OFPRAW_OFPT12_ROLE_REPLY, request, 0);
4895         orr = ofpbuf_put_zeros(buf, sizeof *orr);
4896
4897         orr->role = htonl(rr->role);
4898         orr->generation_id = htonll(rr->have_generation_id
4899                                     ? rr->generation_id
4900                                     : UINT64_MAX);
4901     } else if (raw == OFPRAW_NXT_ROLE_REQUEST) {
4902         struct nx_role_request *nrr;
4903
4904         BUILD_ASSERT(NX_ROLE_OTHER == OFPCR12_ROLE_EQUAL - 1);
4905         BUILD_ASSERT(NX_ROLE_MASTER == OFPCR12_ROLE_MASTER - 1);
4906         BUILD_ASSERT(NX_ROLE_SLAVE == OFPCR12_ROLE_SLAVE - 1);
4907
4908         buf = ofpraw_alloc_reply(OFPRAW_NXT_ROLE_REPLY, request, 0);
4909         nrr = ofpbuf_put_zeros(buf, sizeof *nrr);
4910         nrr->role = htonl(rr->role - 1);
4911     } else {
4912         OVS_NOT_REACHED();
4913     }
4914
4915     return buf;
4916 }
4917 \f
4918 struct ofpbuf *
4919 ofputil_encode_role_status(const struct ofputil_role_status *status,
4920                            enum ofputil_protocol protocol)
4921 {
4922     struct ofpbuf *buf;
4923     enum ofp_version version;
4924     struct ofp14_role_status *rstatus;
4925
4926     version = ofputil_protocol_to_ofp_version(protocol);
4927     buf = ofpraw_alloc_xid(OFPRAW_OFPT14_ROLE_STATUS, version, htonl(0), 0);
4928     rstatus = ofpbuf_put_zeros(buf, sizeof *rstatus);
4929     rstatus->role = htonl(status->role);
4930     rstatus->reason = status->reason;
4931     rstatus->generation_id = htonll(status->generation_id);
4932
4933     return buf;
4934 }
4935
4936 enum ofperr
4937 ofputil_decode_role_status(const struct ofp_header *oh,
4938                            struct ofputil_role_status *rs)
4939 {
4940     struct ofpbuf b;
4941     enum ofpraw raw;
4942     const struct ofp14_role_status *r;
4943
4944     ofpbuf_use_const(&b, oh, ntohs(oh->length));
4945     raw = ofpraw_pull_assert(&b);
4946     ovs_assert(raw == OFPRAW_OFPT14_ROLE_STATUS);
4947
4948     r = ofpbuf_l3(&b);
4949     if (r->role != htonl(OFPCR12_ROLE_NOCHANGE) &&
4950         r->role != htonl(OFPCR12_ROLE_EQUAL) &&
4951         r->role != htonl(OFPCR12_ROLE_MASTER) &&
4952         r->role != htonl(OFPCR12_ROLE_SLAVE)) {
4953         return OFPERR_OFPRRFC_BAD_ROLE;
4954     }
4955
4956     rs->role = ntohl(r->role);
4957     rs->generation_id = ntohll(r->generation_id);
4958     rs->reason = r->reason;
4959
4960     return 0;
4961 }
4962
4963 /* Table stats. */
4964
4965 static void
4966 ofputil_put_ofp10_table_stats(const struct ofp12_table_stats *in,
4967                               struct ofpbuf *buf)
4968 {
4969     struct wc_map {
4970         enum ofp10_flow_wildcards wc10;
4971         enum oxm12_ofb_match_fields mf12;
4972     };
4973
4974     static const struct wc_map wc_map[] = {
4975         { OFPFW10_IN_PORT,     OFPXMT12_OFB_IN_PORT },
4976         { OFPFW10_DL_VLAN,     OFPXMT12_OFB_VLAN_VID },
4977         { OFPFW10_DL_SRC,      OFPXMT12_OFB_ETH_SRC },
4978         { OFPFW10_DL_DST,      OFPXMT12_OFB_ETH_DST},
4979         { OFPFW10_DL_TYPE,     OFPXMT12_OFB_ETH_TYPE },
4980         { OFPFW10_NW_PROTO,    OFPXMT12_OFB_IP_PROTO },
4981         { OFPFW10_TP_SRC,      OFPXMT12_OFB_TCP_SRC },
4982         { OFPFW10_TP_DST,      OFPXMT12_OFB_TCP_DST },
4983         { OFPFW10_NW_SRC_MASK, OFPXMT12_OFB_IPV4_SRC },
4984         { OFPFW10_NW_DST_MASK, OFPXMT12_OFB_IPV4_DST },
4985         { OFPFW10_DL_VLAN_PCP, OFPXMT12_OFB_VLAN_PCP },
4986         { OFPFW10_NW_TOS,      OFPXMT12_OFB_IP_DSCP },
4987     };
4988
4989     struct ofp10_table_stats *out;
4990     const struct wc_map *p;
4991
4992     out = ofpbuf_put_zeros(buf, sizeof *out);
4993     out->table_id = in->table_id;
4994     ovs_strlcpy(out->name, in->name, sizeof out->name);
4995     out->wildcards = 0;
4996     for (p = wc_map; p < &wc_map[ARRAY_SIZE(wc_map)]; p++) {
4997         if (in->wildcards & htonll(1ULL << p->mf12)) {
4998             out->wildcards |= htonl(p->wc10);
4999         }
5000     }
5001     out->max_entries = in->max_entries;
5002     out->active_count = in->active_count;
5003     put_32aligned_be64(&out->lookup_count, in->lookup_count);
5004     put_32aligned_be64(&out->matched_count, in->matched_count);
5005 }
5006
5007 static ovs_be32
5008 oxm12_to_ofp11_flow_match_fields(ovs_be64 oxm12)
5009 {
5010     struct map {
5011         enum ofp11_flow_match_fields fmf11;
5012         enum oxm12_ofb_match_fields mf12;
5013     };
5014
5015     static const struct map map[] = {
5016         { OFPFMF11_IN_PORT,     OFPXMT12_OFB_IN_PORT },
5017         { OFPFMF11_DL_VLAN,     OFPXMT12_OFB_VLAN_VID },
5018         { OFPFMF11_DL_VLAN_PCP, OFPXMT12_OFB_VLAN_PCP },
5019         { OFPFMF11_DL_TYPE,     OFPXMT12_OFB_ETH_TYPE },
5020         { OFPFMF11_NW_TOS,      OFPXMT12_OFB_IP_DSCP },
5021         { OFPFMF11_NW_PROTO,    OFPXMT12_OFB_IP_PROTO },
5022         { OFPFMF11_TP_SRC,      OFPXMT12_OFB_TCP_SRC },
5023         { OFPFMF11_TP_DST,      OFPXMT12_OFB_TCP_DST },
5024         { OFPFMF11_MPLS_LABEL,  OFPXMT12_OFB_MPLS_LABEL },
5025         { OFPFMF11_MPLS_TC,     OFPXMT12_OFB_MPLS_TC },
5026         /* I don't know what OFPFMF11_TYPE means. */
5027         { OFPFMF11_DL_SRC,      OFPXMT12_OFB_ETH_SRC },
5028         { OFPFMF11_DL_DST,      OFPXMT12_OFB_ETH_DST },
5029         { OFPFMF11_NW_SRC,      OFPXMT12_OFB_IPV4_SRC },
5030         { OFPFMF11_NW_DST,      OFPXMT12_OFB_IPV4_DST },
5031         { OFPFMF11_METADATA,    OFPXMT12_OFB_METADATA },
5032     };
5033
5034     const struct map *p;
5035     uint32_t fmf11;
5036
5037     fmf11 = 0;
5038     for (p = map; p < &map[ARRAY_SIZE(map)]; p++) {
5039         if (oxm12 & htonll(1ULL << p->mf12)) {
5040             fmf11 |= p->fmf11;
5041         }
5042     }
5043     return htonl(fmf11);
5044 }
5045
5046 static void
5047 ofputil_put_ofp11_table_stats(const struct ofp12_table_stats *in,
5048                               struct ofpbuf *buf)
5049 {
5050     struct ofp11_table_stats *out;
5051
5052     out = ofpbuf_put_zeros(buf, sizeof *out);
5053     out->table_id = in->table_id;
5054     ovs_strlcpy(out->name, in->name, sizeof out->name);
5055     out->wildcards = oxm12_to_ofp11_flow_match_fields(in->wildcards);
5056     out->match = oxm12_to_ofp11_flow_match_fields(in->match);
5057     out->instructions = in->instructions;
5058     out->write_actions = in->write_actions;
5059     out->apply_actions = in->apply_actions;
5060     out->config = in->config;
5061     out->max_entries = in->max_entries;
5062     out->active_count = in->active_count;
5063     out->lookup_count = in->lookup_count;
5064     out->matched_count = in->matched_count;
5065 }
5066
5067 static void
5068 ofputil_put_ofp12_table_stats(const struct ofp12_table_stats *in,
5069                               struct ofpbuf *buf)
5070 {
5071     struct ofp12_table_stats *out = ofpbuf_put(buf, in, sizeof *in);
5072
5073     /* Trim off OF1.3-only capabilities. */
5074     out->match &= htonll(OFPXMT12_MASK);
5075     out->wildcards &= htonll(OFPXMT12_MASK);
5076     out->write_setfields &= htonll(OFPXMT12_MASK);
5077     out->apply_setfields &= htonll(OFPXMT12_MASK);
5078 }
5079
5080 static void
5081 ofputil_put_ofp13_table_stats(const struct ofp12_table_stats *in,
5082                               struct ofpbuf *buf)
5083 {
5084     struct ofp13_table_stats *out;
5085
5086     /* OF 1.3 splits table features off the ofp_table_stats,
5087      * so there is not much here. */
5088
5089     out = ofpbuf_put_uninit(buf, sizeof *out);
5090     out->table_id = in->table_id;
5091     out->active_count = in->active_count;
5092     out->lookup_count = in->lookup_count;
5093     out->matched_count = in->matched_count;
5094 }
5095
5096 struct ofpbuf *
5097 ofputil_encode_table_stats_reply(const struct ofp12_table_stats stats[], int n,
5098                                  const struct ofp_header *request)
5099 {
5100     struct ofpbuf *reply;
5101     int i;
5102
5103     reply = ofpraw_alloc_stats_reply(request, n * sizeof *stats);
5104
5105     for (i = 0; i < n; i++) {
5106         switch ((enum ofp_version) request->version) {
5107         case OFP10_VERSION:
5108             ofputil_put_ofp10_table_stats(&stats[i], reply);
5109             break;
5110
5111         case OFP11_VERSION:
5112             ofputil_put_ofp11_table_stats(&stats[i], reply);
5113             break;
5114
5115         case OFP12_VERSION:
5116             ofputil_put_ofp12_table_stats(&stats[i], reply);
5117             break;
5118
5119         case OFP13_VERSION:
5120         case OFP14_VERSION:
5121         case OFP15_VERSION:
5122             ofputil_put_ofp13_table_stats(&stats[i], reply);
5123             break;
5124
5125         default:
5126             OVS_NOT_REACHED();
5127         }
5128     }
5129
5130     return reply;
5131 }
5132 \f
5133 /* ofputil_flow_monitor_request */
5134
5135 /* Converts an NXST_FLOW_MONITOR request in 'msg' into an abstract
5136  * ofputil_flow_monitor_request in 'rq'.
5137  *
5138  * Multiple NXST_FLOW_MONITOR requests can be packed into a single OpenFlow
5139  * message.  Calling this function multiple times for a single 'msg' iterates
5140  * through the requests.  The caller must initially leave 'msg''s layer
5141  * pointers null and not modify them between calls.
5142  *
5143  * Returns 0 if successful, EOF if no requests were left in this 'msg',
5144  * otherwise an OFPERR_* value. */
5145 int
5146 ofputil_decode_flow_monitor_request(struct ofputil_flow_monitor_request *rq,
5147                                     struct ofpbuf *msg)
5148 {
5149     struct nx_flow_monitor_request *nfmr;
5150     uint16_t flags;
5151
5152     if (!msg->frame) {
5153         ofpraw_pull_assert(msg);
5154     }
5155
5156     if (!ofpbuf_size(msg)) {
5157         return EOF;
5158     }
5159
5160     nfmr = ofpbuf_try_pull(msg, sizeof *nfmr);
5161     if (!nfmr) {
5162         VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR request has %"PRIu32" "
5163                      "leftover bytes at end", ofpbuf_size(msg));
5164         return OFPERR_OFPBRC_BAD_LEN;
5165     }
5166
5167     flags = ntohs(nfmr->flags);
5168     if (!(flags & (NXFMF_ADD | NXFMF_DELETE | NXFMF_MODIFY))
5169         || flags & ~(NXFMF_INITIAL | NXFMF_ADD | NXFMF_DELETE
5170                      | NXFMF_MODIFY | NXFMF_ACTIONS | NXFMF_OWN)) {
5171         VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR has bad flags %#"PRIx16,
5172                      flags);
5173         return OFPERR_NXBRC_FM_BAD_FLAGS;
5174     }
5175
5176     if (!is_all_zeros(nfmr->zeros, sizeof nfmr->zeros)) {
5177         return OFPERR_NXBRC_MUST_BE_ZERO;
5178     }
5179
5180     rq->id = ntohl(nfmr->id);
5181     rq->flags = flags;
5182     rq->out_port = u16_to_ofp(ntohs(nfmr->out_port));
5183     rq->table_id = nfmr->table_id;
5184
5185     return nx_pull_match(msg, ntohs(nfmr->match_len), &rq->match, NULL, NULL);
5186 }
5187
5188 void
5189 ofputil_append_flow_monitor_request(
5190     const struct ofputil_flow_monitor_request *rq, struct ofpbuf *msg)
5191 {
5192     struct nx_flow_monitor_request *nfmr;
5193     size_t start_ofs;
5194     int match_len;
5195
5196     if (!ofpbuf_size(msg)) {
5197         ofpraw_put(OFPRAW_NXST_FLOW_MONITOR_REQUEST, OFP10_VERSION, msg);
5198     }
5199
5200     start_ofs = ofpbuf_size(msg);
5201     ofpbuf_put_zeros(msg, sizeof *nfmr);
5202     match_len = nx_put_match(msg, &rq->match, htonll(0), htonll(0));
5203
5204     nfmr = ofpbuf_at_assert(msg, start_ofs, sizeof *nfmr);
5205     nfmr->id = htonl(rq->id);
5206     nfmr->flags = htons(rq->flags);
5207     nfmr->out_port = htons(ofp_to_u16(rq->out_port));
5208     nfmr->match_len = htons(match_len);
5209     nfmr->table_id = rq->table_id;
5210 }
5211
5212 /* Converts an NXST_FLOW_MONITOR reply (also known as a flow update) in 'msg'
5213  * into an abstract ofputil_flow_update in 'update'.  The caller must have
5214  * initialized update->match to point to space allocated for a match.
5215  *
5216  * Uses 'ofpacts' to store the abstract OFPACT_* version of the update's
5217  * actions (except for NXFME_ABBREV, which never includes actions).  The caller
5218  * must initialize 'ofpacts' and retains ownership of it.  'update->ofpacts'
5219  * will point into the 'ofpacts' buffer.
5220  *
5221  * Multiple flow updates can be packed into a single OpenFlow message.  Calling
5222  * this function multiple times for a single 'msg' iterates through the
5223  * updates.  The caller must initially leave 'msg''s layer pointers null and
5224  * not modify them between calls.
5225  *
5226  * Returns 0 if successful, EOF if no updates were left in this 'msg',
5227  * otherwise an OFPERR_* value. */
5228 int
5229 ofputil_decode_flow_update(struct ofputil_flow_update *update,
5230                            struct ofpbuf *msg, struct ofpbuf *ofpacts)
5231 {
5232     struct nx_flow_update_header *nfuh;
5233     unsigned int length;
5234     struct ofp_header *oh;
5235
5236     if (!msg->frame) {
5237         ofpraw_pull_assert(msg);
5238     }
5239
5240     if (!ofpbuf_size(msg)) {
5241         return EOF;
5242     }
5243
5244     if (ofpbuf_size(msg) < sizeof(struct nx_flow_update_header)) {
5245         goto bad_len;
5246     }
5247
5248     oh = msg->frame;
5249
5250     nfuh = ofpbuf_data(msg);
5251     update->event = ntohs(nfuh->event);
5252     length = ntohs(nfuh->length);
5253     if (length > ofpbuf_size(msg) || length % 8) {
5254         goto bad_len;
5255     }
5256
5257     if (update->event == NXFME_ABBREV) {
5258         struct nx_flow_update_abbrev *nfua;
5259
5260         if (length != sizeof *nfua) {
5261             goto bad_len;
5262         }
5263
5264         nfua = ofpbuf_pull(msg, sizeof *nfua);
5265         update->xid = nfua->xid;
5266         return 0;
5267     } else if (update->event == NXFME_ADDED
5268                || update->event == NXFME_DELETED
5269                || update->event == NXFME_MODIFIED) {
5270         struct nx_flow_update_full *nfuf;
5271         unsigned int actions_len;
5272         unsigned int match_len;
5273         enum ofperr error;
5274
5275         if (length < sizeof *nfuf) {
5276             goto bad_len;
5277         }
5278
5279         nfuf = ofpbuf_pull(msg, sizeof *nfuf);
5280         match_len = ntohs(nfuf->match_len);
5281         if (sizeof *nfuf + match_len > length) {
5282             goto bad_len;
5283         }
5284
5285         update->reason = ntohs(nfuf->reason);
5286         update->idle_timeout = ntohs(nfuf->idle_timeout);
5287         update->hard_timeout = ntohs(nfuf->hard_timeout);
5288         update->table_id = nfuf->table_id;
5289         update->cookie = nfuf->cookie;
5290         update->priority = ntohs(nfuf->priority);
5291
5292         error = nx_pull_match(msg, match_len, update->match, NULL, NULL);
5293         if (error) {
5294             return error;
5295         }
5296
5297         actions_len = length - sizeof *nfuf - ROUND_UP(match_len, 8);
5298         error = ofpacts_pull_openflow_actions(msg, actions_len, oh->version,
5299                                               ofpacts);
5300         if (error) {
5301             return error;
5302         }
5303
5304         update->ofpacts = ofpbuf_data(ofpacts);
5305         update->ofpacts_len = ofpbuf_size(ofpacts);
5306         return 0;
5307     } else {
5308         VLOG_WARN_RL(&bad_ofmsg_rl,
5309                      "NXST_FLOW_MONITOR reply has bad event %"PRIu16,
5310                      ntohs(nfuh->event));
5311         return OFPERR_NXBRC_FM_BAD_EVENT;
5312     }
5313
5314 bad_len:
5315     VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR reply has %"PRIu32" "
5316                  "leftover bytes at end", ofpbuf_size(msg));
5317     return OFPERR_OFPBRC_BAD_LEN;
5318 }
5319
5320 uint32_t
5321 ofputil_decode_flow_monitor_cancel(const struct ofp_header *oh)
5322 {
5323     const struct nx_flow_monitor_cancel *cancel = ofpmsg_body(oh);
5324
5325     return ntohl(cancel->id);
5326 }
5327
5328 struct ofpbuf *
5329 ofputil_encode_flow_monitor_cancel(uint32_t id)
5330 {
5331     struct nx_flow_monitor_cancel *nfmc;
5332     struct ofpbuf *msg;
5333
5334     msg = ofpraw_alloc(OFPRAW_NXT_FLOW_MONITOR_CANCEL, OFP10_VERSION, 0);
5335     nfmc = ofpbuf_put_uninit(msg, sizeof *nfmc);
5336     nfmc->id = htonl(id);
5337     return msg;
5338 }
5339
5340 void
5341 ofputil_start_flow_update(struct list *replies)
5342 {
5343     struct ofpbuf *msg;
5344
5345     msg = ofpraw_alloc_xid(OFPRAW_NXST_FLOW_MONITOR_REPLY, OFP10_VERSION,
5346                            htonl(0), 1024);
5347
5348     list_init(replies);
5349     list_push_back(replies, &msg->list_node);
5350 }
5351
5352 void
5353 ofputil_append_flow_update(const struct ofputil_flow_update *update,
5354                            struct list *replies)
5355 {
5356     enum ofp_version version = ofpmp_version(replies);
5357     struct nx_flow_update_header *nfuh;
5358     struct ofpbuf *msg;
5359     size_t start_ofs;
5360
5361     msg = ofpbuf_from_list(list_back(replies));
5362     start_ofs = ofpbuf_size(msg);
5363
5364     if (update->event == NXFME_ABBREV) {
5365         struct nx_flow_update_abbrev *nfua;
5366
5367         nfua = ofpbuf_put_zeros(msg, sizeof *nfua);
5368         nfua->xid = update->xid;
5369     } else {
5370         struct nx_flow_update_full *nfuf;
5371         int match_len;
5372
5373         ofpbuf_put_zeros(msg, sizeof *nfuf);
5374         match_len = nx_put_match(msg, update->match, htonll(0), htonll(0));
5375         ofpacts_put_openflow_actions(update->ofpacts, update->ofpacts_len, msg,
5376                                      version);
5377         nfuf = ofpbuf_at_assert(msg, start_ofs, sizeof *nfuf);
5378         nfuf->reason = htons(update->reason);
5379         nfuf->priority = htons(update->priority);
5380         nfuf->idle_timeout = htons(update->idle_timeout);
5381         nfuf->hard_timeout = htons(update->hard_timeout);
5382         nfuf->match_len = htons(match_len);
5383         nfuf->table_id = update->table_id;
5384         nfuf->cookie = update->cookie;
5385     }
5386
5387     nfuh = ofpbuf_at_assert(msg, start_ofs, sizeof *nfuh);
5388     nfuh->length = htons(ofpbuf_size(msg) - start_ofs);
5389     nfuh->event = htons(update->event);
5390
5391     ofpmp_postappend(replies, start_ofs);
5392 }
5393 \f
5394 struct ofpbuf *
5395 ofputil_encode_packet_out(const struct ofputil_packet_out *po,
5396                           enum ofputil_protocol protocol)
5397 {
5398     enum ofp_version ofp_version = ofputil_protocol_to_ofp_version(protocol);
5399     struct ofpbuf *msg;
5400     size_t size;
5401
5402     size = po->ofpacts_len;
5403     if (po->buffer_id == UINT32_MAX) {
5404         size += po->packet_len;
5405     }
5406
5407     switch (ofp_version) {
5408     case OFP10_VERSION: {
5409         struct ofp10_packet_out *opo;
5410         size_t actions_ofs;
5411
5412         msg = ofpraw_alloc(OFPRAW_OFPT10_PACKET_OUT, OFP10_VERSION, size);
5413         ofpbuf_put_zeros(msg, sizeof *opo);
5414         actions_ofs = ofpbuf_size(msg);
5415         ofpacts_put_openflow_actions(po->ofpacts, po->ofpacts_len, msg,
5416                                      ofp_version);
5417
5418         opo = ofpbuf_l3(msg);
5419         opo->buffer_id = htonl(po->buffer_id);
5420         opo->in_port = htons(ofp_to_u16(po->in_port));
5421         opo->actions_len = htons(ofpbuf_size(msg) - actions_ofs);
5422         break;
5423     }
5424
5425     case OFP11_VERSION:
5426     case OFP12_VERSION:
5427     case OFP13_VERSION:
5428     case OFP14_VERSION:
5429     case OFP15_VERSION: {
5430         struct ofp11_packet_out *opo;
5431         size_t len;
5432
5433         msg = ofpraw_alloc(OFPRAW_OFPT11_PACKET_OUT, ofp_version, size);
5434         ofpbuf_put_zeros(msg, sizeof *opo);
5435         len = ofpacts_put_openflow_actions(po->ofpacts, po->ofpacts_len, msg,
5436                                            ofp_version);
5437         opo = ofpbuf_l3(msg);
5438         opo->buffer_id = htonl(po->buffer_id);
5439         opo->in_port = ofputil_port_to_ofp11(po->in_port);
5440         opo->actions_len = htons(len);
5441         break;
5442     }
5443
5444     default:
5445         OVS_NOT_REACHED();
5446     }
5447
5448     if (po->buffer_id == UINT32_MAX) {
5449         ofpbuf_put(msg, po->packet, po->packet_len);
5450     }
5451
5452     ofpmsg_update_length(msg);
5453
5454     return msg;
5455 }
5456 \f
5457 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
5458 struct ofpbuf *
5459 make_echo_request(enum ofp_version ofp_version)
5460 {
5461     return ofpraw_alloc_xid(OFPRAW_OFPT_ECHO_REQUEST, ofp_version,
5462                             htonl(0), 0);
5463 }
5464
5465 /* Creates and returns an OFPT_ECHO_REPLY message matching the
5466  * OFPT_ECHO_REQUEST message in 'rq'. */
5467 struct ofpbuf *
5468 make_echo_reply(const struct ofp_header *rq)
5469 {
5470     struct ofpbuf rq_buf;
5471     struct ofpbuf *reply;
5472
5473     ofpbuf_use_const(&rq_buf, rq, ntohs(rq->length));
5474     ofpraw_pull_assert(&rq_buf);
5475
5476     reply = ofpraw_alloc_reply(OFPRAW_OFPT_ECHO_REPLY, rq, ofpbuf_size(&rq_buf));
5477     ofpbuf_put(reply, ofpbuf_data(&rq_buf), ofpbuf_size(&rq_buf));
5478     return reply;
5479 }
5480
5481 struct ofpbuf *
5482 ofputil_encode_barrier_request(enum ofp_version ofp_version)
5483 {
5484     enum ofpraw type;
5485
5486     switch (ofp_version) {
5487     case OFP15_VERSION:
5488     case OFP14_VERSION:
5489     case OFP13_VERSION:
5490     case OFP12_VERSION:
5491     case OFP11_VERSION:
5492         type = OFPRAW_OFPT11_BARRIER_REQUEST;
5493         break;
5494
5495     case OFP10_VERSION:
5496         type = OFPRAW_OFPT10_BARRIER_REQUEST;
5497         break;
5498
5499     default:
5500         OVS_NOT_REACHED();
5501     }
5502
5503     return ofpraw_alloc(type, ofp_version, 0);
5504 }
5505
5506 const char *
5507 ofputil_frag_handling_to_string(enum ofp_config_flags flags)
5508 {
5509     switch (flags & OFPC_FRAG_MASK) {
5510     case OFPC_FRAG_NORMAL:   return "normal";
5511     case OFPC_FRAG_DROP:     return "drop";
5512     case OFPC_FRAG_REASM:    return "reassemble";
5513     case OFPC_FRAG_NX_MATCH: return "nx-match";
5514     }
5515
5516     OVS_NOT_REACHED();
5517 }
5518
5519 bool
5520 ofputil_frag_handling_from_string(const char *s, enum ofp_config_flags *flags)
5521 {
5522     if (!strcasecmp(s, "normal")) {
5523         *flags = OFPC_FRAG_NORMAL;
5524     } else if (!strcasecmp(s, "drop")) {
5525         *flags = OFPC_FRAG_DROP;
5526     } else if (!strcasecmp(s, "reassemble")) {
5527         *flags = OFPC_FRAG_REASM;
5528     } else if (!strcasecmp(s, "nx-match")) {
5529         *flags = OFPC_FRAG_NX_MATCH;
5530     } else {
5531         return false;
5532     }
5533     return true;
5534 }
5535
5536 /* Converts the OpenFlow 1.1+ port number 'ofp11_port' into an OpenFlow 1.0
5537  * port number and stores the latter in '*ofp10_port', for the purpose of
5538  * decoding OpenFlow 1.1+ protocol messages.  Returns 0 if successful,
5539  * otherwise an OFPERR_* number.  On error, stores OFPP_NONE in '*ofp10_port'.
5540  *
5541  * See the definition of OFP11_MAX for an explanation of the mapping. */
5542 enum ofperr
5543 ofputil_port_from_ofp11(ovs_be32 ofp11_port, ofp_port_t *ofp10_port)
5544 {
5545     uint32_t ofp11_port_h = ntohl(ofp11_port);
5546
5547     if (ofp11_port_h < ofp_to_u16(OFPP_MAX)) {
5548         *ofp10_port = u16_to_ofp(ofp11_port_h);
5549         return 0;
5550     } else if (ofp11_port_h >= ofp11_to_u32(OFPP11_MAX)) {
5551         *ofp10_port = u16_to_ofp(ofp11_port_h - OFPP11_OFFSET);
5552         return 0;
5553     } else {
5554         *ofp10_port = OFPP_NONE;
5555         VLOG_WARN_RL(&bad_ofmsg_rl, "port %"PRIu32" is outside the supported "
5556                      "range 0 through %d or 0x%"PRIx32" through 0x%"PRIx32,
5557                      ofp11_port_h, ofp_to_u16(OFPP_MAX) - 1,
5558                      ofp11_to_u32(OFPP11_MAX), UINT32_MAX);
5559         return OFPERR_OFPBAC_BAD_OUT_PORT;
5560     }
5561 }
5562
5563 /* Returns the OpenFlow 1.1+ port number equivalent to the OpenFlow 1.0 port
5564  * number 'ofp10_port', for encoding OpenFlow 1.1+ protocol messages.
5565  *
5566  * See the definition of OFP11_MAX for an explanation of the mapping. */
5567 ovs_be32
5568 ofputil_port_to_ofp11(ofp_port_t ofp10_port)
5569 {
5570     return htonl(ofp_to_u16(ofp10_port) < ofp_to_u16(OFPP_MAX)
5571                  ? ofp_to_u16(ofp10_port)
5572                  : ofp_to_u16(ofp10_port) + OFPP11_OFFSET);
5573 }
5574
5575 #define OFPUTIL_NAMED_PORTS                     \
5576         OFPUTIL_NAMED_PORT(IN_PORT)             \
5577         OFPUTIL_NAMED_PORT(TABLE)               \
5578         OFPUTIL_NAMED_PORT(NORMAL)              \
5579         OFPUTIL_NAMED_PORT(FLOOD)               \
5580         OFPUTIL_NAMED_PORT(ALL)                 \
5581         OFPUTIL_NAMED_PORT(CONTROLLER)          \
5582         OFPUTIL_NAMED_PORT(LOCAL)               \
5583         OFPUTIL_NAMED_PORT(ANY)
5584
5585 /* For backwards compatibility, so that "none" is recognized as OFPP_ANY */
5586 #define OFPUTIL_NAMED_PORTS_WITH_NONE           \
5587         OFPUTIL_NAMED_PORTS                     \
5588         OFPUTIL_NAMED_PORT(NONE)
5589
5590 /* Stores the port number represented by 's' into '*portp'.  's' may be an
5591  * integer or, for reserved ports, the standard OpenFlow name for the port
5592  * (e.g. "LOCAL").
5593  *
5594  * Returns true if successful, false if 's' is not a valid OpenFlow port number
5595  * or name.  The caller should issue an error message in this case, because
5596  * this function usually does not.  (This gives the caller an opportunity to
5597  * look up the port name another way, e.g. by contacting the switch and listing
5598  * the names of all its ports).
5599  *
5600  * This function accepts OpenFlow 1.0 port numbers.  It also accepts a subset
5601  * of OpenFlow 1.1+ port numbers, mapping those port numbers into the 16-bit
5602  * range as described in include/openflow/openflow-1.1.h. */
5603 bool
5604 ofputil_port_from_string(const char *s, ofp_port_t *portp)
5605 {
5606     unsigned int port32; /* int is at least 32 bits wide. */
5607
5608     if (*s == '-') {
5609         VLOG_WARN("Negative value %s is not a valid port number.", s);
5610         return false;
5611     }
5612     *portp = 0;
5613     if (str_to_uint(s, 10, &port32)) {
5614         if (port32 < ofp_to_u16(OFPP_MAX)) {
5615             /* Pass. */
5616         } else if (port32 < ofp_to_u16(OFPP_FIRST_RESV)) {
5617             VLOG_WARN("port %u is a reserved OF1.0 port number that will "
5618                       "be translated to %u when talking to an OF1.1 or "
5619                       "later controller", port32, port32 + OFPP11_OFFSET);
5620         } else if (port32 <= ofp_to_u16(OFPP_LAST_RESV)) {
5621             char name[OFP_MAX_PORT_NAME_LEN];
5622
5623             ofputil_port_to_string(u16_to_ofp(port32), name, sizeof name);
5624             VLOG_WARN_ONCE("referring to port %s as %"PRIu32" is deprecated "
5625                            "for compatibility with OpenFlow 1.1 and later",
5626                            name, port32);
5627         } else if (port32 < ofp11_to_u32(OFPP11_MAX)) {
5628             VLOG_WARN("port %u is outside the supported range 0 through "
5629                       "%"PRIx16" or 0x%x through 0x%"PRIx32, port32,
5630                       UINT16_MAX, ofp11_to_u32(OFPP11_MAX), UINT32_MAX);
5631             return false;
5632         } else {
5633             port32 -= OFPP11_OFFSET;
5634         }
5635
5636         *portp = u16_to_ofp(port32);
5637         return true;
5638     } else {
5639         struct pair {
5640             const char *name;
5641             ofp_port_t value;
5642         };
5643         static const struct pair pairs[] = {
5644 #define OFPUTIL_NAMED_PORT(NAME) {#NAME, OFPP_##NAME},
5645             OFPUTIL_NAMED_PORTS_WITH_NONE
5646 #undef OFPUTIL_NAMED_PORT
5647         };
5648         const struct pair *p;
5649
5650         for (p = pairs; p < &pairs[ARRAY_SIZE(pairs)]; p++) {
5651             if (!strcasecmp(s, p->name)) {
5652                 *portp = p->value;
5653                 return true;
5654             }
5655         }
5656         return false;
5657     }
5658 }
5659
5660 /* Appends to 's' a string representation of the OpenFlow port number 'port'.
5661  * Most ports' string representation is just the port number, but for special
5662  * ports, e.g. OFPP_LOCAL, it is the name, e.g. "LOCAL". */
5663 void
5664 ofputil_format_port(ofp_port_t port, struct ds *s)
5665 {
5666     char name[OFP_MAX_PORT_NAME_LEN];
5667
5668     ofputil_port_to_string(port, name, sizeof name);
5669     ds_put_cstr(s, name);
5670 }
5671
5672 /* Puts in the 'bufsize' byte in 'namebuf' a null-terminated string
5673  * representation of OpenFlow port number 'port'.  Most ports are represented
5674  * as just the port number, but special ports, e.g. OFPP_LOCAL, are represented
5675  * by name, e.g. "LOCAL". */
5676 void
5677 ofputil_port_to_string(ofp_port_t port,
5678                        char namebuf[OFP_MAX_PORT_NAME_LEN], size_t bufsize)
5679 {
5680     switch (port) {
5681 #define OFPUTIL_NAMED_PORT(NAME)                        \
5682         case OFPP_##NAME:                               \
5683             ovs_strlcpy(namebuf, #NAME, bufsize);       \
5684             break;
5685         OFPUTIL_NAMED_PORTS
5686 #undef OFPUTIL_NAMED_PORT
5687
5688     default:
5689         snprintf(namebuf, bufsize, "%"PRIu16, port);
5690         break;
5691     }
5692 }
5693
5694 /* Stores the group id represented by 's' into '*group_idp'.  's' may be an
5695  * integer or, for reserved group IDs, the standard OpenFlow name for the group
5696  * (either "ANY" or "ALL").
5697  *
5698  * Returns true if successful, false if 's' is not a valid OpenFlow group ID or
5699  * name. */
5700 bool
5701 ofputil_group_from_string(const char *s, uint32_t *group_idp)
5702 {
5703     if (!strcasecmp(s, "any")) {
5704         *group_idp = OFPG11_ANY;
5705     } else if (!strcasecmp(s, "all")) {
5706         *group_idp = OFPG11_ALL;
5707     } else if (!str_to_uint(s, 10, group_idp)) {
5708         VLOG_WARN("%s is not a valid group ID.  (Valid group IDs are "
5709                   "32-bit nonnegative integers or the keywords ANY or "
5710                   "ALL.)", s);
5711         return false;
5712     }
5713
5714     return true;
5715 }
5716
5717 /* Appends to 's' a string representation of the OpenFlow group ID 'group_id'.
5718  * Most groups' string representation is just the number, but for special
5719  * groups, e.g. OFPG11_ALL, it is the name, e.g. "ALL". */
5720 void
5721 ofputil_format_group(uint32_t group_id, struct ds *s)
5722 {
5723     char name[MAX_GROUP_NAME_LEN];
5724
5725     ofputil_group_to_string(group_id, name, sizeof name);
5726     ds_put_cstr(s, name);
5727 }
5728
5729
5730 /* Puts in the 'bufsize' byte in 'namebuf' a null-terminated string
5731  * representation of OpenFlow group ID 'group_id'.  Most group are represented
5732  * as just their number, but special groups, e.g. OFPG11_ALL, are represented
5733  * by name, e.g. "ALL". */
5734 void
5735 ofputil_group_to_string(uint32_t group_id,
5736                         char namebuf[MAX_GROUP_NAME_LEN + 1], size_t bufsize)
5737 {
5738     switch (group_id) {
5739     case OFPG11_ALL:
5740         ovs_strlcpy(namebuf, "ALL", bufsize);
5741         break;
5742
5743     case OFPG11_ANY:
5744         ovs_strlcpy(namebuf, "ANY", bufsize);
5745         break;
5746
5747     default:
5748         snprintf(namebuf, bufsize, "%"PRIu32, group_id);
5749         break;
5750     }
5751 }
5752
5753 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
5754  * 'ofp_version', tries to pull the first element from the array.  If
5755  * successful, initializes '*pp' with an abstract representation of the
5756  * port and returns 0.  If no ports remain to be decoded, returns EOF.
5757  * On an error, returns a positive OFPERR_* value. */
5758 int
5759 ofputil_pull_phy_port(enum ofp_version ofp_version, struct ofpbuf *b,
5760                       struct ofputil_phy_port *pp)
5761 {
5762     memset(pp, 0, sizeof *pp);
5763
5764     switch (ofp_version) {
5765     case OFP10_VERSION: {
5766         const struct ofp10_phy_port *opp = ofpbuf_try_pull(b, sizeof *opp);
5767         return opp ? ofputil_decode_ofp10_phy_port(pp, opp) : EOF;
5768     }
5769     case OFP11_VERSION:
5770     case OFP12_VERSION:
5771     case OFP13_VERSION: {
5772         const struct ofp11_port *op = ofpbuf_try_pull(b, sizeof *op);
5773         return op ? ofputil_decode_ofp11_port(pp, op) : EOF;
5774     }
5775     case OFP14_VERSION:
5776     case OFP15_VERSION:
5777         return ofpbuf_size(b) ? ofputil_pull_ofp14_port(pp, b) : EOF;
5778     default:
5779         OVS_NOT_REACHED();
5780     }
5781 }
5782
5783 /* ofp-util.def lists the mapping from names to action. */
5784 static const char *const names[OFPUTIL_N_ACTIONS] = {
5785     NULL,
5786 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)             NAME,
5787 #define OFPAT11_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) NAME,
5788 #define OFPAT13_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) NAME,
5789 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)   NAME,
5790 #include "ofp-util.def"
5791 };
5792
5793 /* Returns the 'enum ofputil_action_code' corresponding to 'name' (e.g. if
5794  * 'name' is "output" then the return value is OFPUTIL_OFPAT10_OUTPUT), or -1
5795  * if 'name' is not the name of any action. */
5796 int
5797 ofputil_action_code_from_name(const char *name)
5798 {
5799     const char *const *p;
5800
5801     for (p = names; p < &names[ARRAY_SIZE(names)]; p++) {
5802         if (*p && !strcasecmp(name, *p)) {
5803             return p - names;
5804         }
5805     }
5806     return -1;
5807 }
5808
5809 /* Returns name corresponding to the 'enum ofputil_action_code',
5810  * or "Unkonwn action", if the name is not available. */
5811 const char *
5812 ofputil_action_name_from_code(enum ofputil_action_code code)
5813 {
5814     return code < (int)OFPUTIL_N_ACTIONS && names[code] ? names[code]
5815         : "Unknown action";
5816 }
5817
5818 enum ofputil_action_code
5819 ofputil_action_code_from_ofp13_action(enum ofp13_action_type type)
5820 {
5821     switch (type) {
5822
5823 #define OFPAT13_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)  \
5824     case ENUM:                                          \
5825         return OFPUTIL_##ENUM;
5826 #include "ofp-util.def"
5827
5828     default:
5829         return OFPUTIL_ACTION_INVALID;
5830     }
5831 }
5832
5833 /* Appends an action of the type specified by 'code' to 'buf' and returns the
5834  * action.  Initializes the parts of 'action' that identify it as having type
5835  * <ENUM> and length 'sizeof *action' and zeros the rest.  For actions that
5836  * have variable length, the length used and cleared is that of struct
5837  * <STRUCT>.  */
5838 void *
5839 ofputil_put_action(enum ofputil_action_code code, struct ofpbuf *buf)
5840 {
5841     switch (code) {
5842     case OFPUTIL_ACTION_INVALID:
5843 #define OFPAT13_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) case OFPUTIL_##ENUM:
5844 #include "ofp-util.def"
5845         OVS_NOT_REACHED();
5846
5847 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                  \
5848     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
5849 #define OFPAT11_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)      \
5850     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
5851 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)        \
5852     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
5853 #include "ofp-util.def"
5854     }
5855     OVS_NOT_REACHED();
5856 }
5857
5858 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                        \
5859     void                                                        \
5860     ofputil_init_##ENUM(struct STRUCT *s)                       \
5861     {                                                           \
5862         memset(s, 0, sizeof *s);                                \
5863         s->type = htons(ENUM);                                  \
5864         s->len = htons(sizeof *s);                              \
5865     }                                                           \
5866                                                                 \
5867     struct STRUCT *                                             \
5868     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
5869     {                                                           \
5870         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
5871         ofputil_init_##ENUM(s);                                 \
5872         return s;                                               \
5873     }
5874 #define OFPAT11_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) \
5875     OFPAT10_ACTION(ENUM, STRUCT, NAME)
5876 #define OFPAT13_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) \
5877     OFPAT10_ACTION(ENUM, STRUCT, NAME)
5878 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)            \
5879     void                                                        \
5880     ofputil_init_##ENUM(struct STRUCT *s)                       \
5881     {                                                           \
5882         memset(s, 0, sizeof *s);                                \
5883         s->type = htons(OFPAT10_VENDOR);                        \
5884         s->len = htons(sizeof *s);                              \
5885         s->vendor = htonl(NX_VENDOR_ID);                        \
5886         s->subtype = htons(ENUM);                               \
5887     }                                                           \
5888                                                                 \
5889     struct STRUCT *                                             \
5890     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
5891     {                                                           \
5892         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
5893         ofputil_init_##ENUM(s);                                 \
5894         return s;                                               \
5895     }
5896 #include "ofp-util.def"
5897
5898 static void
5899 ofputil_normalize_match__(struct match *match, bool may_log)
5900 {
5901     enum {
5902         MAY_NW_ADDR     = 1 << 0, /* nw_src, nw_dst */
5903         MAY_TP_ADDR     = 1 << 1, /* tp_src, tp_dst */
5904         MAY_NW_PROTO    = 1 << 2, /* nw_proto */
5905         MAY_IPVx        = 1 << 3, /* tos, frag, ttl */
5906         MAY_ARP_SHA     = 1 << 4, /* arp_sha */
5907         MAY_ARP_THA     = 1 << 5, /* arp_tha */
5908         MAY_IPV6        = 1 << 6, /* ipv6_src, ipv6_dst, ipv6_label */
5909         MAY_ND_TARGET   = 1 << 7, /* nd_target */
5910         MAY_MPLS        = 1 << 8, /* mpls label and tc */
5911     } may_match;
5912
5913     struct flow_wildcards wc;
5914
5915     /* Figure out what fields may be matched. */
5916     if (match->flow.dl_type == htons(ETH_TYPE_IP)) {
5917         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_NW_ADDR;
5918         if (match->flow.nw_proto == IPPROTO_TCP ||
5919             match->flow.nw_proto == IPPROTO_UDP ||
5920             match->flow.nw_proto == IPPROTO_SCTP ||
5921             match->flow.nw_proto == IPPROTO_ICMP) {
5922             may_match |= MAY_TP_ADDR;
5923         }
5924     } else if (match->flow.dl_type == htons(ETH_TYPE_IPV6)) {
5925         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_IPV6;
5926         if (match->flow.nw_proto == IPPROTO_TCP ||
5927             match->flow.nw_proto == IPPROTO_UDP ||
5928             match->flow.nw_proto == IPPROTO_SCTP) {
5929             may_match |= MAY_TP_ADDR;
5930         } else if (match->flow.nw_proto == IPPROTO_ICMPV6) {
5931             may_match |= MAY_TP_ADDR;
5932             if (match->flow.tp_src == htons(ND_NEIGHBOR_SOLICIT)) {
5933                 may_match |= MAY_ND_TARGET | MAY_ARP_SHA;
5934             } else if (match->flow.tp_src == htons(ND_NEIGHBOR_ADVERT)) {
5935                 may_match |= MAY_ND_TARGET | MAY_ARP_THA;
5936             }
5937         }
5938     } else if (match->flow.dl_type == htons(ETH_TYPE_ARP) ||
5939                match->flow.dl_type == htons(ETH_TYPE_RARP)) {
5940         may_match = MAY_NW_PROTO | MAY_NW_ADDR | MAY_ARP_SHA | MAY_ARP_THA;
5941     } else if (eth_type_mpls(match->flow.dl_type)) {
5942         may_match = MAY_MPLS;
5943     } else {
5944         may_match = 0;
5945     }
5946
5947     /* Clear the fields that may not be matched. */
5948     wc = match->wc;
5949     if (!(may_match & MAY_NW_ADDR)) {
5950         wc.masks.nw_src = wc.masks.nw_dst = htonl(0);
5951     }
5952     if (!(may_match & MAY_TP_ADDR)) {
5953         wc.masks.tp_src = wc.masks.tp_dst = htons(0);
5954     }
5955     if (!(may_match & MAY_NW_PROTO)) {
5956         wc.masks.nw_proto = 0;
5957     }
5958     if (!(may_match & MAY_IPVx)) {
5959         wc.masks.nw_tos = 0;
5960         wc.masks.nw_ttl = 0;
5961     }
5962     if (!(may_match & MAY_ARP_SHA)) {
5963         memset(wc.masks.arp_sha, 0, ETH_ADDR_LEN);
5964     }
5965     if (!(may_match & MAY_ARP_THA)) {
5966         memset(wc.masks.arp_tha, 0, ETH_ADDR_LEN);
5967     }
5968     if (!(may_match & MAY_IPV6)) {
5969         wc.masks.ipv6_src = wc.masks.ipv6_dst = in6addr_any;
5970         wc.masks.ipv6_label = htonl(0);
5971     }
5972     if (!(may_match & MAY_ND_TARGET)) {
5973         wc.masks.nd_target = in6addr_any;
5974     }
5975     if (!(may_match & MAY_MPLS)) {
5976         memset(wc.masks.mpls_lse, 0, sizeof wc.masks.mpls_lse);
5977     }
5978
5979     /* Log any changes. */
5980     if (!flow_wildcards_equal(&wc, &match->wc)) {
5981         bool log = may_log && !VLOG_DROP_INFO(&bad_ofmsg_rl);
5982         char *pre = log ? match_to_string(match, OFP_DEFAULT_PRIORITY) : NULL;
5983
5984         match->wc = wc;
5985         match_zero_wildcarded_fields(match);
5986
5987         if (log) {
5988             char *post = match_to_string(match, OFP_DEFAULT_PRIORITY);
5989             VLOG_INFO("normalization changed ofp_match, details:");
5990             VLOG_INFO(" pre: %s", pre);
5991             VLOG_INFO("post: %s", post);
5992             free(pre);
5993             free(post);
5994         }
5995     }
5996 }
5997
5998 /* "Normalizes" the wildcards in 'match'.  That means:
5999  *
6000  *    1. If the type of level N is known, then only the valid fields for that
6001  *       level may be specified.  For example, ARP does not have a TOS field,
6002  *       so nw_tos must be wildcarded if 'match' specifies an ARP flow.
6003  *       Similarly, IPv4 does not have any IPv6 addresses, so ipv6_src and
6004  *       ipv6_dst (and other fields) must be wildcarded if 'match' specifies an
6005  *       IPv4 flow.
6006  *
6007  *    2. If the type of level N is not known (or not understood by Open
6008  *       vSwitch), then no fields at all for that level may be specified.  For
6009  *       example, Open vSwitch does not understand SCTP, an L4 protocol, so the
6010  *       L4 fields tp_src and tp_dst must be wildcarded if 'match' specifies an
6011  *       SCTP flow.
6012  *
6013  * If this function changes 'match', it logs a rate-limited informational
6014  * message. */
6015 void
6016 ofputil_normalize_match(struct match *match)
6017 {
6018     ofputil_normalize_match__(match, true);
6019 }
6020
6021 /* Same as ofputil_normalize_match() without the logging.  Thus, this function
6022  * is suitable for a program's internal use, whereas ofputil_normalize_match()
6023  * sense for use on flows received from elsewhere (so that a bug in the program
6024  * that sent them can be reported and corrected). */
6025 void
6026 ofputil_normalize_match_quiet(struct match *match)
6027 {
6028     ofputil_normalize_match__(match, false);
6029 }
6030
6031 /* Parses a key or a key-value pair from '*stringp'.
6032  *
6033  * On success: Stores the key into '*keyp'.  Stores the value, if present, into
6034  * '*valuep', otherwise an empty string.  Advances '*stringp' past the end of
6035  * the key-value pair, preparing it for another call.  '*keyp' and '*valuep'
6036  * are substrings of '*stringp' created by replacing some of its bytes by null
6037  * terminators.  Returns true.
6038  *
6039  * If '*stringp' is just white space or commas, sets '*keyp' and '*valuep' to
6040  * NULL and returns false. */
6041 bool
6042 ofputil_parse_key_value(char **stringp, char **keyp, char **valuep)
6043 {
6044     char *pos, *key, *value;
6045     size_t key_len;
6046
6047     pos = *stringp;
6048     pos += strspn(pos, ", \t\r\n");
6049     if (*pos == '\0') {
6050         *keyp = *valuep = NULL;
6051         return false;
6052     }
6053
6054     key = pos;
6055     key_len = strcspn(pos, ":=(, \t\r\n");
6056     if (key[key_len] == ':' || key[key_len] == '=') {
6057         /* The value can be separated by a colon. */
6058         size_t value_len;
6059
6060         value = key + key_len + 1;
6061         value_len = strcspn(value, ", \t\r\n");
6062         pos = value + value_len + (value[value_len] != '\0');
6063         value[value_len] = '\0';
6064     } else if (key[key_len] == '(') {
6065         /* The value can be surrounded by balanced parentheses.  The outermost
6066          * set of parentheses is removed. */
6067         int level = 1;
6068         size_t value_len;
6069
6070         value = key + key_len + 1;
6071         for (value_len = 0; level > 0; value_len++) {
6072             switch (value[value_len]) {
6073             case '\0':
6074                 level = 0;
6075                 break;
6076
6077             case '(':
6078                 level++;
6079                 break;
6080
6081             case ')':
6082                 level--;
6083                 break;
6084             }
6085         }
6086         value[value_len - 1] = '\0';
6087         pos = value + value_len;
6088     } else {
6089         /* There might be no value at all. */
6090         value = key + key_len;  /* Will become the empty string below. */
6091         pos = key + key_len + (key[key_len] != '\0');
6092     }
6093     key[key_len] = '\0';
6094
6095     *stringp = pos;
6096     *keyp = key;
6097     *valuep = value;
6098     return true;
6099 }
6100
6101 /* Encode a dump ports request for 'port', the encoded message
6102  * will be for Open Flow version 'ofp_version'. Returns message
6103  * as a struct ofpbuf. Returns encoded message on success, NULL on error */
6104 struct ofpbuf *
6105 ofputil_encode_dump_ports_request(enum ofp_version ofp_version, ofp_port_t port)
6106 {
6107     struct ofpbuf *request;
6108
6109     switch (ofp_version) {
6110     case OFP10_VERSION: {
6111         struct ofp10_port_stats_request *req;
6112         request = ofpraw_alloc(OFPRAW_OFPST10_PORT_REQUEST, ofp_version, 0);
6113         req = ofpbuf_put_zeros(request, sizeof *req);
6114         req->port_no = htons(ofp_to_u16(port));
6115         break;
6116     }
6117     case OFP11_VERSION:
6118     case OFP12_VERSION:
6119     case OFP13_VERSION:
6120     case OFP14_VERSION:
6121     case OFP15_VERSION: {
6122         struct ofp11_port_stats_request *req;
6123         request = ofpraw_alloc(OFPRAW_OFPST11_PORT_REQUEST, ofp_version, 0);
6124         req = ofpbuf_put_zeros(request, sizeof *req);
6125         req->port_no = ofputil_port_to_ofp11(port);
6126         break;
6127     }
6128     default:
6129         OVS_NOT_REACHED();
6130     }
6131
6132     return request;
6133 }
6134
6135 static void
6136 ofputil_port_stats_to_ofp10(const struct ofputil_port_stats *ops,
6137                             struct ofp10_port_stats *ps10)
6138 {
6139     ps10->port_no = htons(ofp_to_u16(ops->port_no));
6140     memset(ps10->pad, 0, sizeof ps10->pad);
6141     put_32aligned_be64(&ps10->rx_packets, htonll(ops->stats.rx_packets));
6142     put_32aligned_be64(&ps10->tx_packets, htonll(ops->stats.tx_packets));
6143     put_32aligned_be64(&ps10->rx_bytes, htonll(ops->stats.rx_bytes));
6144     put_32aligned_be64(&ps10->tx_bytes, htonll(ops->stats.tx_bytes));
6145     put_32aligned_be64(&ps10->rx_dropped, htonll(ops->stats.rx_dropped));
6146     put_32aligned_be64(&ps10->tx_dropped, htonll(ops->stats.tx_dropped));
6147     put_32aligned_be64(&ps10->rx_errors, htonll(ops->stats.rx_errors));
6148     put_32aligned_be64(&ps10->tx_errors, htonll(ops->stats.tx_errors));
6149     put_32aligned_be64(&ps10->rx_frame_err, htonll(ops->stats.rx_frame_errors));
6150     put_32aligned_be64(&ps10->rx_over_err, htonll(ops->stats.rx_over_errors));
6151     put_32aligned_be64(&ps10->rx_crc_err, htonll(ops->stats.rx_crc_errors));
6152     put_32aligned_be64(&ps10->collisions, htonll(ops->stats.collisions));
6153 }
6154
6155 static void
6156 ofputil_port_stats_to_ofp11(const struct ofputil_port_stats *ops,
6157                             struct ofp11_port_stats *ps11)
6158 {
6159     ps11->port_no = ofputil_port_to_ofp11(ops->port_no);
6160     memset(ps11->pad, 0, sizeof ps11->pad);
6161     ps11->rx_packets = htonll(ops->stats.rx_packets);
6162     ps11->tx_packets = htonll(ops->stats.tx_packets);
6163     ps11->rx_bytes = htonll(ops->stats.rx_bytes);
6164     ps11->tx_bytes = htonll(ops->stats.tx_bytes);
6165     ps11->rx_dropped = htonll(ops->stats.rx_dropped);
6166     ps11->tx_dropped = htonll(ops->stats.tx_dropped);
6167     ps11->rx_errors = htonll(ops->stats.rx_errors);
6168     ps11->tx_errors = htonll(ops->stats.tx_errors);
6169     ps11->rx_frame_err = htonll(ops->stats.rx_frame_errors);
6170     ps11->rx_over_err = htonll(ops->stats.rx_over_errors);
6171     ps11->rx_crc_err = htonll(ops->stats.rx_crc_errors);
6172     ps11->collisions = htonll(ops->stats.collisions);
6173 }
6174
6175 static void
6176 ofputil_port_stats_to_ofp13(const struct ofputil_port_stats *ops,
6177                             struct ofp13_port_stats *ps13)
6178 {
6179     ofputil_port_stats_to_ofp11(ops, &ps13->ps);
6180     ps13->duration_sec = htonl(ops->duration_sec);
6181     ps13->duration_nsec = htonl(ops->duration_nsec);
6182 }
6183
6184 static void
6185 ofputil_append_ofp14_port_stats(const struct ofputil_port_stats *ops,
6186                                 struct list *replies)
6187 {
6188     struct ofp14_port_stats_prop_ethernet *eth;
6189     struct ofp14_port_stats *ps14;
6190     struct ofpbuf *reply;
6191
6192     reply = ofpmp_reserve(replies, sizeof *ps14 + sizeof *eth);
6193
6194     ps14 = ofpbuf_put_uninit(reply, sizeof *ps14);
6195     ps14->length = htons(sizeof *ps14 + sizeof *eth);
6196     memset(ps14->pad, 0, sizeof ps14->pad);
6197     ps14->port_no = ofputil_port_to_ofp11(ops->port_no);
6198     ps14->duration_sec = htonl(ops->duration_sec);
6199     ps14->duration_nsec = htonl(ops->duration_nsec);
6200     ps14->rx_packets = htonll(ops->stats.rx_packets);
6201     ps14->tx_packets = htonll(ops->stats.tx_packets);
6202     ps14->rx_bytes = htonll(ops->stats.rx_bytes);
6203     ps14->tx_bytes = htonll(ops->stats.tx_bytes);
6204     ps14->rx_dropped = htonll(ops->stats.rx_dropped);
6205     ps14->tx_dropped = htonll(ops->stats.tx_dropped);
6206     ps14->rx_errors = htonll(ops->stats.rx_errors);
6207     ps14->tx_errors = htonll(ops->stats.tx_errors);
6208
6209     eth = ofpbuf_put_uninit(reply, sizeof *eth);
6210     eth->type = htons(OFPPSPT14_ETHERNET);
6211     eth->length = htons(sizeof *eth);
6212     memset(eth->pad, 0, sizeof eth->pad);
6213     eth->rx_frame_err = htonll(ops->stats.rx_frame_errors);
6214     eth->rx_over_err = htonll(ops->stats.rx_over_errors);
6215     eth->rx_crc_err = htonll(ops->stats.rx_crc_errors);
6216     eth->collisions = htonll(ops->stats.collisions);
6217 }
6218
6219 /* Encode a ports stat for 'ops' and append it to 'replies'. */
6220 void
6221 ofputil_append_port_stat(struct list *replies,
6222                          const struct ofputil_port_stats *ops)
6223 {
6224     switch (ofpmp_version(replies)) {
6225     case OFP13_VERSION: {
6226         struct ofp13_port_stats *reply = ofpmp_append(replies, sizeof *reply);
6227         ofputil_port_stats_to_ofp13(ops, reply);
6228         break;
6229     }
6230     case OFP12_VERSION:
6231     case OFP11_VERSION: {
6232         struct ofp11_port_stats *reply = ofpmp_append(replies, sizeof *reply);
6233         ofputil_port_stats_to_ofp11(ops, reply);
6234         break;
6235     }
6236
6237     case OFP10_VERSION: {
6238         struct ofp10_port_stats *reply = ofpmp_append(replies, sizeof *reply);
6239         ofputil_port_stats_to_ofp10(ops, reply);
6240         break;
6241     }
6242
6243     case OFP14_VERSION:
6244     case OFP15_VERSION:
6245         ofputil_append_ofp14_port_stats(ops, replies);
6246         break;
6247
6248     default:
6249         OVS_NOT_REACHED();
6250     }
6251 }
6252
6253 static enum ofperr
6254 ofputil_port_stats_from_ofp10(struct ofputil_port_stats *ops,
6255                               const struct ofp10_port_stats *ps10)
6256 {
6257     memset(ops, 0, sizeof *ops);
6258
6259     ops->port_no = u16_to_ofp(ntohs(ps10->port_no));
6260     ops->stats.rx_packets = ntohll(get_32aligned_be64(&ps10->rx_packets));
6261     ops->stats.tx_packets = ntohll(get_32aligned_be64(&ps10->tx_packets));
6262     ops->stats.rx_bytes = ntohll(get_32aligned_be64(&ps10->rx_bytes));
6263     ops->stats.tx_bytes = ntohll(get_32aligned_be64(&ps10->tx_bytes));
6264     ops->stats.rx_dropped = ntohll(get_32aligned_be64(&ps10->rx_dropped));
6265     ops->stats.tx_dropped = ntohll(get_32aligned_be64(&ps10->tx_dropped));
6266     ops->stats.rx_errors = ntohll(get_32aligned_be64(&ps10->rx_errors));
6267     ops->stats.tx_errors = ntohll(get_32aligned_be64(&ps10->tx_errors));
6268     ops->stats.rx_frame_errors =
6269         ntohll(get_32aligned_be64(&ps10->rx_frame_err));
6270     ops->stats.rx_over_errors = ntohll(get_32aligned_be64(&ps10->rx_over_err));
6271     ops->stats.rx_crc_errors = ntohll(get_32aligned_be64(&ps10->rx_crc_err));
6272     ops->stats.collisions = ntohll(get_32aligned_be64(&ps10->collisions));
6273     ops->duration_sec = ops->duration_nsec = UINT32_MAX;
6274
6275     return 0;
6276 }
6277
6278 static enum ofperr
6279 ofputil_port_stats_from_ofp11(struct ofputil_port_stats *ops,
6280                               const struct ofp11_port_stats *ps11)
6281 {
6282     enum ofperr error;
6283
6284     memset(ops, 0, sizeof *ops);
6285     error = ofputil_port_from_ofp11(ps11->port_no, &ops->port_no);
6286     if (error) {
6287         return error;
6288     }
6289
6290     ops->stats.rx_packets = ntohll(ps11->rx_packets);
6291     ops->stats.tx_packets = ntohll(ps11->tx_packets);
6292     ops->stats.rx_bytes = ntohll(ps11->rx_bytes);
6293     ops->stats.tx_bytes = ntohll(ps11->tx_bytes);
6294     ops->stats.rx_dropped = ntohll(ps11->rx_dropped);
6295     ops->stats.tx_dropped = ntohll(ps11->tx_dropped);
6296     ops->stats.rx_errors = ntohll(ps11->rx_errors);
6297     ops->stats.tx_errors = ntohll(ps11->tx_errors);
6298     ops->stats.rx_frame_errors = ntohll(ps11->rx_frame_err);
6299     ops->stats.rx_over_errors = ntohll(ps11->rx_over_err);
6300     ops->stats.rx_crc_errors = ntohll(ps11->rx_crc_err);
6301     ops->stats.collisions = ntohll(ps11->collisions);
6302     ops->duration_sec = ops->duration_nsec = UINT32_MAX;
6303
6304     return 0;
6305 }
6306
6307 static enum ofperr
6308 ofputil_port_stats_from_ofp13(struct ofputil_port_stats *ops,
6309                               const struct ofp13_port_stats *ps13)
6310 {
6311     enum ofperr error = ofputil_port_stats_from_ofp11(ops, &ps13->ps);
6312     if (!error) {
6313         ops->duration_sec = ntohl(ps13->duration_sec);
6314         ops->duration_nsec = ntohl(ps13->duration_nsec);
6315     }
6316     return error;
6317 }
6318
6319 static enum ofperr
6320 parse_ofp14_port_stats_ethernet_property(const struct ofpbuf *payload,
6321                                          struct ofputil_port_stats *ops)
6322 {
6323     const struct ofp14_port_stats_prop_ethernet *eth = ofpbuf_data(payload);
6324
6325     if (ofpbuf_size(payload) != sizeof *eth) {
6326         return OFPERR_OFPBPC_BAD_LEN;
6327     }
6328
6329     ops->stats.rx_frame_errors = ntohll(eth->rx_frame_err);
6330     ops->stats.rx_over_errors = ntohll(eth->rx_over_err);
6331     ops->stats.rx_crc_errors = ntohll(eth->rx_crc_err);
6332     ops->stats.collisions = ntohll(eth->collisions);
6333
6334     return 0;
6335 }
6336
6337 static enum ofperr
6338 ofputil_pull_ofp14_port_stats(struct ofputil_port_stats *ops,
6339                               struct ofpbuf *msg)
6340 {
6341     const struct ofp14_port_stats *ps14;
6342     struct ofpbuf properties;
6343     enum ofperr error;
6344     size_t len;
6345
6346     ps14 = ofpbuf_try_pull(msg, sizeof *ps14);
6347     if (!ps14) {
6348         return OFPERR_OFPBRC_BAD_LEN;
6349     }
6350
6351     len = ntohs(ps14->length);
6352     if (len < sizeof *ps14 || len - sizeof *ps14 > ofpbuf_size(msg)) {
6353         return OFPERR_OFPBRC_BAD_LEN;
6354     }
6355     len -= sizeof *ps14;
6356     ofpbuf_use_const(&properties, ofpbuf_pull(msg, len), len);
6357
6358     error = ofputil_port_from_ofp11(ps14->port_no, &ops->port_no);
6359     if (error) {
6360         return error;
6361     }
6362
6363     ops->duration_sec = ntohl(ps14->duration_sec);
6364     ops->duration_nsec = ntohl(ps14->duration_nsec);
6365     ops->stats.rx_packets = ntohll(ps14->rx_packets);
6366     ops->stats.tx_packets = ntohll(ps14->tx_packets);
6367     ops->stats.rx_bytes = ntohll(ps14->rx_bytes);
6368     ops->stats.tx_bytes = ntohll(ps14->tx_bytes);
6369     ops->stats.rx_dropped = ntohll(ps14->rx_dropped);
6370     ops->stats.tx_dropped = ntohll(ps14->tx_dropped);
6371     ops->stats.rx_errors = ntohll(ps14->rx_errors);
6372     ops->stats.tx_errors = ntohll(ps14->tx_errors);
6373     ops->stats.rx_frame_errors = UINT64_MAX;
6374     ops->stats.rx_over_errors = UINT64_MAX;
6375     ops->stats.rx_crc_errors = UINT64_MAX;
6376     ops->stats.collisions = UINT64_MAX;
6377
6378     while (ofpbuf_size(&properties) > 0) {
6379         struct ofpbuf payload;
6380         enum ofperr error;
6381         uint16_t type;
6382
6383         error = ofputil_pull_property(&properties, &payload, &type);
6384         if (error) {
6385             return error;
6386         }
6387
6388         switch (type) {
6389         case OFPPSPT14_ETHERNET:
6390             error = parse_ofp14_port_stats_ethernet_property(&payload, ops);
6391             break;
6392
6393         default:
6394             log_property(true, "unknown port stats property %"PRIu16, type);
6395             error = 0;
6396             break;
6397         }
6398
6399         if (error) {
6400             return error;
6401         }
6402     }
6403
6404     return 0;
6405 }
6406
6407 /* Returns the number of port stats elements in OFPTYPE_PORT_STATS_REPLY
6408  * message 'oh'. */
6409 size_t
6410 ofputil_count_port_stats(const struct ofp_header *oh)
6411 {
6412     struct ofputil_port_stats ps;
6413     struct ofpbuf b;
6414     size_t n = 0;
6415
6416     ofpbuf_use_const(&b, oh, ntohs(oh->length));
6417     ofpraw_pull_assert(&b);
6418     while (!ofputil_decode_port_stats(&ps, &b)) {
6419         n++;
6420     }
6421     return n;
6422 }
6423
6424 /* Converts an OFPST_PORT_STATS reply in 'msg' into an abstract
6425  * ofputil_port_stats in 'ps'.
6426  *
6427  * Multiple OFPST_PORT_STATS replies can be packed into a single OpenFlow
6428  * message.  Calling this function multiple times for a single 'msg' iterates
6429  * through the replies.  The caller must initially leave 'msg''s layer pointers
6430  * null and not modify them between calls.
6431  *
6432  * Returns 0 if successful, EOF if no replies were left in this 'msg',
6433  * otherwise a positive errno value. */
6434 int
6435 ofputil_decode_port_stats(struct ofputil_port_stats *ps, struct ofpbuf *msg)
6436 {
6437     enum ofperr error;
6438     enum ofpraw raw;
6439
6440     error = (msg->frame
6441              ? ofpraw_decode(&raw, msg->frame)
6442              : ofpraw_pull(&raw, msg));
6443     if (error) {
6444         return error;
6445     }
6446
6447     if (!ofpbuf_size(msg)) {
6448         return EOF;
6449     } else if (raw == OFPRAW_OFPST14_PORT_REPLY) {
6450         return ofputil_pull_ofp14_port_stats(ps, msg);
6451     } else if (raw == OFPRAW_OFPST13_PORT_REPLY) {
6452         const struct ofp13_port_stats *ps13;
6453
6454         ps13 = ofpbuf_try_pull(msg, sizeof *ps13);
6455         if (!ps13) {
6456             goto bad_len;
6457         }
6458         return ofputil_port_stats_from_ofp13(ps, ps13);
6459     } else if (raw == OFPRAW_OFPST11_PORT_REPLY) {
6460         const struct ofp11_port_stats *ps11;
6461
6462         ps11 = ofpbuf_try_pull(msg, sizeof *ps11);
6463         if (!ps11) {
6464             goto bad_len;
6465         }
6466         return ofputil_port_stats_from_ofp11(ps, ps11);
6467     } else if (raw == OFPRAW_OFPST10_PORT_REPLY) {
6468         const struct ofp10_port_stats *ps10;
6469
6470         ps10 = ofpbuf_try_pull(msg, sizeof *ps10);
6471         if (!ps10) {
6472             goto bad_len;
6473         }
6474         return ofputil_port_stats_from_ofp10(ps, ps10);
6475     } else {
6476         OVS_NOT_REACHED();
6477     }
6478
6479  bad_len:
6480     VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_PORT reply has %"PRIu32" leftover "
6481                  "bytes at end", ofpbuf_size(msg));
6482     return OFPERR_OFPBRC_BAD_LEN;
6483 }
6484
6485 /* Parse a port status request message into a 16 bit OpenFlow 1.0
6486  * port number and stores the latter in '*ofp10_port'.
6487  * Returns 0 if successful, otherwise an OFPERR_* number. */
6488 enum ofperr
6489 ofputil_decode_port_stats_request(const struct ofp_header *request,
6490                                   ofp_port_t *ofp10_port)
6491 {
6492     switch ((enum ofp_version)request->version) {
6493     case OFP15_VERSION:
6494     case OFP14_VERSION:
6495     case OFP13_VERSION:
6496     case OFP12_VERSION:
6497     case OFP11_VERSION: {
6498         const struct ofp11_port_stats_request *psr11 = ofpmsg_body(request);
6499         return ofputil_port_from_ofp11(psr11->port_no, ofp10_port);
6500     }
6501
6502     case OFP10_VERSION: {
6503         const struct ofp10_port_stats_request *psr10 = ofpmsg_body(request);
6504         *ofp10_port = u16_to_ofp(ntohs(psr10->port_no));
6505         return 0;
6506     }
6507
6508     default:
6509         OVS_NOT_REACHED();
6510     }
6511 }
6512
6513 /* Frees all of the "struct ofputil_bucket"s in the 'buckets' list. */
6514 void
6515 ofputil_bucket_list_destroy(struct list *buckets)
6516 {
6517     struct ofputil_bucket *bucket, *next_bucket;
6518
6519     LIST_FOR_EACH_SAFE (bucket, next_bucket, list_node, buckets) {
6520         list_remove(&bucket->list_node);
6521         free(bucket->ofpacts);
6522         free(bucket);
6523     }
6524 }
6525
6526 /* Returns an OpenFlow group stats request for OpenFlow version 'ofp_version',
6527  * that requests stats for group 'group_id'.  (Use OFPG_ALL to request stats
6528  * for all groups.)
6529  *
6530  * Group statistics include packet and byte counts for each group. */
6531 struct ofpbuf *
6532 ofputil_encode_group_stats_request(enum ofp_version ofp_version,
6533                                    uint32_t group_id)
6534 {
6535     struct ofpbuf *request;
6536
6537     switch (ofp_version) {
6538     case OFP10_VERSION:
6539         ovs_fatal(0, "dump-group-stats needs OpenFlow 1.1 or later "
6540                      "(\'-O OpenFlow11\')");
6541     case OFP11_VERSION:
6542     case OFP12_VERSION:
6543     case OFP13_VERSION:
6544     case OFP14_VERSION:
6545     case OFP15_VERSION: {
6546         struct ofp11_group_stats_request *req;
6547         request = ofpraw_alloc(OFPRAW_OFPST11_GROUP_REQUEST, ofp_version, 0);
6548         req = ofpbuf_put_zeros(request, sizeof *req);
6549         req->group_id = htonl(group_id);
6550         break;
6551     }
6552     default:
6553         OVS_NOT_REACHED();
6554     }
6555
6556     return request;
6557 }
6558
6559 /* Returns an OpenFlow group description request for OpenFlow version
6560  * 'ofp_version', that requests stats for group 'group_id'.  (Use OFPG_ALL to
6561  * request stats for all groups.)
6562  *
6563  * Group descriptions include the bucket and action configuration for each
6564  * group. */
6565 struct ofpbuf *
6566 ofputil_encode_group_desc_request(enum ofp_version ofp_version)
6567 {
6568     struct ofpbuf *request;
6569
6570     switch (ofp_version) {
6571     case OFP10_VERSION:
6572         ovs_fatal(0, "dump-groups needs OpenFlow 1.1 or later "
6573                      "(\'-O OpenFlow11\')");
6574     case OFP11_VERSION:
6575     case OFP12_VERSION:
6576     case OFP13_VERSION:
6577     case OFP14_VERSION:
6578     case OFP15_VERSION:
6579         request = ofpraw_alloc(OFPRAW_OFPST11_GROUP_DESC_REQUEST, ofp_version, 0);
6580         break;
6581     default:
6582         OVS_NOT_REACHED();
6583     }
6584
6585     return request;
6586 }
6587
6588 static void
6589 ofputil_group_bucket_counters_to_ofp11(const struct ofputil_group_stats *gs,
6590                                     struct ofp11_bucket_counter bucket_cnts[])
6591 {
6592     int i;
6593
6594     for (i = 0; i < gs->n_buckets; i++) {
6595        bucket_cnts[i].packet_count = htonll(gs->bucket_stats[i].packet_count);
6596        bucket_cnts[i].byte_count = htonll(gs->bucket_stats[i].byte_count);
6597     }
6598 }
6599
6600 static void
6601 ofputil_group_stats_to_ofp11(const struct ofputil_group_stats *gs,
6602                              struct ofp11_group_stats *gs11, size_t length,
6603                              struct ofp11_bucket_counter bucket_cnts[])
6604 {
6605     memset(gs11, 0, sizeof *gs11);
6606     gs11->length = htons(length);
6607     gs11->group_id = htonl(gs->group_id);
6608     gs11->ref_count = htonl(gs->ref_count);
6609     gs11->packet_count = htonll(gs->packet_count);
6610     gs11->byte_count = htonll(gs->byte_count);
6611     ofputil_group_bucket_counters_to_ofp11(gs, bucket_cnts);
6612 }
6613
6614 static void
6615 ofputil_group_stats_to_ofp13(const struct ofputil_group_stats *gs,
6616                              struct ofp13_group_stats *gs13, size_t length,
6617                              struct ofp11_bucket_counter bucket_cnts[])
6618 {
6619     ofputil_group_stats_to_ofp11(gs, &gs13->gs, length, bucket_cnts);
6620     gs13->duration_sec = htonl(gs->duration_sec);
6621     gs13->duration_nsec = htonl(gs->duration_nsec);
6622
6623 }
6624
6625 /* Encodes 'gs' properly for the format of the list of group statistics
6626  * replies already begun in 'replies' and appends it to the list.  'replies'
6627  * must have originally been initialized with ofpmp_init(). */
6628 void
6629 ofputil_append_group_stats(struct list *replies,
6630                            const struct ofputil_group_stats *gs)
6631 {
6632     size_t bucket_counter_size;
6633     struct ofp11_bucket_counter *bucket_counters;
6634     size_t length;
6635
6636     bucket_counter_size = gs->n_buckets * sizeof(struct ofp11_bucket_counter);
6637
6638     switch (ofpmp_version(replies)) {
6639     case OFP11_VERSION:
6640     case OFP12_VERSION:{
6641             struct ofp11_group_stats *gs11;
6642
6643             length = sizeof *gs11 + bucket_counter_size;
6644             gs11 = ofpmp_append(replies, length);
6645             bucket_counters = (struct ofp11_bucket_counter *)(gs11 + 1);
6646             ofputil_group_stats_to_ofp11(gs, gs11, length, bucket_counters);
6647             break;
6648         }
6649
6650     case OFP13_VERSION:
6651     case OFP14_VERSION:
6652     case OFP15_VERSION: {
6653             struct ofp13_group_stats *gs13;
6654
6655             length = sizeof *gs13 + bucket_counter_size;
6656             gs13 = ofpmp_append(replies, length);
6657             bucket_counters = (struct ofp11_bucket_counter *)(gs13 + 1);
6658             ofputil_group_stats_to_ofp13(gs, gs13, length, bucket_counters);
6659             break;
6660         }
6661
6662     case OFP10_VERSION:
6663     default:
6664         OVS_NOT_REACHED();
6665     }
6666 }
6667 /* Returns an OpenFlow group features request for OpenFlow version
6668  * 'ofp_version'. */
6669 struct ofpbuf *
6670 ofputil_encode_group_features_request(enum ofp_version ofp_version)
6671 {
6672     struct ofpbuf *request = NULL;
6673
6674     switch (ofp_version) {
6675     case OFP10_VERSION:
6676     case OFP11_VERSION:
6677         ovs_fatal(0, "dump-group-features needs OpenFlow 1.2 or later "
6678                      "(\'-O OpenFlow12\')");
6679     case OFP12_VERSION:
6680     case OFP13_VERSION:
6681     case OFP14_VERSION:
6682     case OFP15_VERSION:
6683         request = ofpraw_alloc(OFPRAW_OFPST12_GROUP_FEATURES_REQUEST,
6684                                ofp_version, 0);
6685         break;
6686     default:
6687         OVS_NOT_REACHED();
6688     }
6689
6690     return request;
6691 }
6692
6693 /* Returns a OpenFlow message that encodes 'features' properly as a reply to
6694  * group features request 'request'. */
6695 struct ofpbuf *
6696 ofputil_encode_group_features_reply(
6697     const struct ofputil_group_features *features,
6698     const struct ofp_header *request)
6699 {
6700     struct ofp12_group_features_stats *ogf;
6701     struct ofpbuf *reply;
6702
6703     reply = ofpraw_alloc_xid(OFPRAW_OFPST12_GROUP_FEATURES_REPLY,
6704                              request->version, request->xid, 0);
6705     ogf = ofpbuf_put_zeros(reply, sizeof *ogf);
6706     ogf->types = htonl(features->types);
6707     ogf->capabilities = htonl(features->capabilities);
6708     ogf->max_groups[0] = htonl(features->max_groups[0]);
6709     ogf->max_groups[1] = htonl(features->max_groups[1]);
6710     ogf->max_groups[2] = htonl(features->max_groups[2]);
6711     ogf->max_groups[3] = htonl(features->max_groups[3]);
6712     ogf->actions[0] = htonl(features->actions[0]);
6713     ogf->actions[1] = htonl(features->actions[1]);
6714     ogf->actions[2] = htonl(features->actions[2]);
6715     ogf->actions[3] = htonl(features->actions[3]);
6716
6717     return reply;
6718 }
6719
6720 /* Decodes group features reply 'oh' into 'features'. */
6721 void
6722 ofputil_decode_group_features_reply(const struct ofp_header *oh,
6723                                     struct ofputil_group_features *features)
6724 {
6725     const struct ofp12_group_features_stats *ogf = ofpmsg_body(oh);
6726
6727     features->types = ntohl(ogf->types);
6728     features->capabilities = ntohl(ogf->capabilities);
6729     features->max_groups[0] = ntohl(ogf->max_groups[0]);
6730     features->max_groups[1] = ntohl(ogf->max_groups[1]);
6731     features->max_groups[2] = ntohl(ogf->max_groups[2]);
6732     features->max_groups[3] = ntohl(ogf->max_groups[3]);
6733     features->actions[0] = ntohl(ogf->actions[0]);
6734     features->actions[1] = ntohl(ogf->actions[1]);
6735     features->actions[2] = ntohl(ogf->actions[2]);
6736     features->actions[3] = ntohl(ogf->actions[3]);
6737 }
6738
6739 /* Parse a group status request message into a 32 bit OpenFlow 1.1
6740  * group ID and stores the latter in '*group_id'.
6741  * Returns 0 if successful, otherwise an OFPERR_* number. */
6742 enum ofperr
6743 ofputil_decode_group_stats_request(const struct ofp_header *request,
6744                                    uint32_t *group_id)
6745 {
6746     const struct ofp11_group_stats_request *gsr11 = ofpmsg_body(request);
6747     *group_id = ntohl(gsr11->group_id);
6748     return 0;
6749 }
6750
6751 /* Converts a group stats reply in 'msg' into an abstract ofputil_group_stats
6752  * in 'gs'.  Assigns freshly allocated memory to gs->bucket_stats for the
6753  * caller to eventually free.
6754  *
6755  * Multiple group stats replies can be packed into a single OpenFlow message.
6756  * Calling this function multiple times for a single 'msg' iterates through the
6757  * replies.  The caller must initially leave 'msg''s layer pointers null and
6758  * not modify them between calls.
6759  *
6760  * Returns 0 if successful, EOF if no replies were left in this 'msg',
6761  * otherwise a positive errno value. */
6762 int
6763 ofputil_decode_group_stats_reply(struct ofpbuf *msg,
6764                                  struct ofputil_group_stats *gs)
6765 {
6766     struct ofp11_bucket_counter *obc;
6767     struct ofp11_group_stats *ogs11;
6768     enum ofpraw raw;
6769     enum ofperr error;
6770     size_t base_len;
6771     size_t length;
6772     size_t i;
6773
6774     gs->bucket_stats = NULL;
6775     error = (msg->frame
6776              ? ofpraw_decode(&raw, msg->frame)
6777              : ofpraw_pull(&raw, msg));
6778     if (error) {
6779         return error;
6780     }
6781
6782     if (!ofpbuf_size(msg)) {
6783         return EOF;
6784     }
6785
6786     if (raw == OFPRAW_OFPST11_GROUP_REPLY) {
6787         base_len = sizeof *ogs11;
6788         ogs11 = ofpbuf_try_pull(msg, sizeof *ogs11);
6789         gs->duration_sec = gs->duration_nsec = UINT32_MAX;
6790     } else if (raw == OFPRAW_OFPST13_GROUP_REPLY) {
6791         struct ofp13_group_stats *ogs13;
6792
6793         base_len = sizeof *ogs13;
6794         ogs13 = ofpbuf_try_pull(msg, sizeof *ogs13);
6795         if (ogs13) {
6796             ogs11 = &ogs13->gs;
6797             gs->duration_sec = ntohl(ogs13->duration_sec);
6798             gs->duration_nsec = ntohl(ogs13->duration_nsec);
6799         } else {
6800             ogs11 = NULL;
6801         }
6802     } else {
6803         OVS_NOT_REACHED();
6804     }
6805
6806     if (!ogs11) {
6807         VLOG_WARN_RL(&bad_ofmsg_rl, "%s reply has %"PRIu32" leftover bytes at end",
6808                      ofpraw_get_name(raw), ofpbuf_size(msg));
6809         return OFPERR_OFPBRC_BAD_LEN;
6810     }
6811     length = ntohs(ogs11->length);
6812     if (length < sizeof base_len) {
6813         VLOG_WARN_RL(&bad_ofmsg_rl, "%s reply claims invalid length %"PRIuSIZE,
6814                      ofpraw_get_name(raw), length);
6815         return OFPERR_OFPBRC_BAD_LEN;
6816     }
6817
6818     gs->group_id = ntohl(ogs11->group_id);
6819     gs->ref_count = ntohl(ogs11->ref_count);
6820     gs->packet_count = ntohll(ogs11->packet_count);
6821     gs->byte_count = ntohll(ogs11->byte_count);
6822
6823     gs->n_buckets = (length - base_len) / sizeof *obc;
6824     obc = ofpbuf_try_pull(msg, gs->n_buckets * sizeof *obc);
6825     if (!obc) {
6826         VLOG_WARN_RL(&bad_ofmsg_rl, "%s reply has %"PRIu32" leftover bytes at end",
6827                      ofpraw_get_name(raw), ofpbuf_size(msg));
6828         return OFPERR_OFPBRC_BAD_LEN;
6829     }
6830
6831     gs->bucket_stats = xmalloc(gs->n_buckets * sizeof *gs->bucket_stats);
6832     for (i = 0; i < gs->n_buckets; i++) {
6833         gs->bucket_stats[i].packet_count = ntohll(obc[i].packet_count);
6834         gs->bucket_stats[i].byte_count = ntohll(obc[i].byte_count);
6835     }
6836
6837     return 0;
6838 }
6839
6840 /* Appends a group stats reply that contains the data in 'gds' to those already
6841  * present in the list of ofpbufs in 'replies'.  'replies' should have been
6842  * initialized with ofpmp_init(). */
6843 void
6844 ofputil_append_group_desc_reply(const struct ofputil_group_desc *gds,
6845                                 struct list *buckets,
6846                                 struct list *replies)
6847 {
6848     struct ofpbuf *reply = ofpbuf_from_list(list_back(replies));
6849     enum ofp_version version = ofpmp_version(replies);
6850     struct ofp11_group_desc_stats *ogds;
6851     struct ofputil_bucket *bucket;
6852     size_t start_ogds;
6853
6854     start_ogds = ofpbuf_size(reply);
6855     ofpbuf_put_zeros(reply, sizeof *ogds);
6856     LIST_FOR_EACH (bucket, list_node, buckets) {
6857         struct ofp11_bucket *ob;
6858         size_t start_ob;
6859
6860         start_ob = ofpbuf_size(reply);
6861         ofpbuf_put_zeros(reply, sizeof *ob);
6862         ofpacts_put_openflow_actions(bucket->ofpacts, bucket->ofpacts_len,
6863                                      reply, version);
6864         ob = ofpbuf_at_assert(reply, start_ob, sizeof *ob);
6865         ob->len = htons(ofpbuf_size(reply) - start_ob);
6866         ob->weight = htons(bucket->weight);
6867         ob->watch_port = ofputil_port_to_ofp11(bucket->watch_port);
6868         ob->watch_group = htonl(bucket->watch_group);
6869     }
6870     ogds = ofpbuf_at_assert(reply, start_ogds, sizeof *ogds);
6871     ogds->length = htons(ofpbuf_size(reply) - start_ogds);
6872     ogds->type = gds->type;
6873     ogds->group_id = htonl(gds->group_id);
6874
6875     ofpmp_postappend(replies, start_ogds);
6876 }
6877
6878 static enum ofperr
6879 ofputil_pull_buckets(struct ofpbuf *msg, size_t buckets_length,
6880                      enum ofp_version version, struct list *buckets)
6881 {
6882     struct ofp11_bucket *ob;
6883
6884     list_init(buckets);
6885     while (buckets_length > 0) {
6886         struct ofputil_bucket *bucket;
6887         struct ofpbuf ofpacts;
6888         enum ofperr error;
6889         size_t ob_len;
6890
6891         ob = (buckets_length >= sizeof *ob
6892               ? ofpbuf_try_pull(msg, sizeof *ob)
6893               : NULL);
6894         if (!ob) {
6895             VLOG_WARN_RL(&bad_ofmsg_rl, "buckets end with %"PRIuSIZE" leftover bytes",
6896                          buckets_length);
6897         }
6898
6899         ob_len = ntohs(ob->len);
6900         if (ob_len < sizeof *ob) {
6901             VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message bucket length "
6902                          "%"PRIuSIZE" is not valid", ob_len);
6903             return OFPERR_OFPGMFC_BAD_BUCKET;
6904         } else if (ob_len > buckets_length) {
6905             VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message bucket length "
6906                          "%"PRIuSIZE" exceeds remaining buckets data size %"PRIuSIZE,
6907                          ob_len, buckets_length);
6908             return OFPERR_OFPGMFC_BAD_BUCKET;
6909         }
6910         buckets_length -= ob_len;
6911
6912         ofpbuf_init(&ofpacts, 0);
6913         error = ofpacts_pull_openflow_actions(msg, ob_len - sizeof *ob,
6914                                               version, &ofpacts);
6915         if (error) {
6916             ofpbuf_uninit(&ofpacts);
6917             ofputil_bucket_list_destroy(buckets);
6918             return error;
6919         }
6920
6921         bucket = xzalloc(sizeof *bucket);
6922         bucket->weight = ntohs(ob->weight);
6923         error = ofputil_port_from_ofp11(ob->watch_port, &bucket->watch_port);
6924         if (error) {
6925             ofpbuf_uninit(&ofpacts);
6926             ofputil_bucket_list_destroy(buckets);
6927             return OFPERR_OFPGMFC_BAD_WATCH;
6928         }
6929         bucket->watch_group = ntohl(ob->watch_group);
6930         bucket->ofpacts = ofpbuf_steal_data(&ofpacts);
6931         bucket->ofpacts_len = ofpbuf_size(&ofpacts);
6932         list_push_back(buckets, &bucket->list_node);
6933     }
6934
6935     return 0;
6936 }
6937
6938 /* Converts a group description reply in 'msg' into an abstract
6939  * ofputil_group_desc in 'gd'.
6940  *
6941  * Multiple group description replies can be packed into a single OpenFlow
6942  * message.  Calling this function multiple times for a single 'msg' iterates
6943  * through the replies.  The caller must initially leave 'msg''s layer pointers
6944  * null and not modify them between calls.
6945  *
6946  * Returns 0 if successful, EOF if no replies were left in this 'msg',
6947  * otherwise a positive errno value. */
6948 int
6949 ofputil_decode_group_desc_reply(struct ofputil_group_desc *gd,
6950                                 struct ofpbuf *msg, enum ofp_version version)
6951 {
6952     struct ofp11_group_desc_stats *ogds;
6953     size_t length;
6954
6955     if (!msg->frame) {
6956         ofpraw_pull_assert(msg);
6957     }
6958
6959     if (!ofpbuf_size(msg)) {
6960         return EOF;
6961     }
6962
6963     ogds = ofpbuf_try_pull(msg, sizeof *ogds);
6964     if (!ogds) {
6965         VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST11_GROUP_DESC reply has %"PRIu32" "
6966                      "leftover bytes at end", ofpbuf_size(msg));
6967         return OFPERR_OFPBRC_BAD_LEN;
6968     }
6969     gd->type = ogds->type;
6970     gd->group_id = ntohl(ogds->group_id);
6971
6972     length = ntohs(ogds->length);
6973     if (length < sizeof *ogds || length - sizeof *ogds > ofpbuf_size(msg)) {
6974         VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST11_GROUP_DESC reply claims invalid "
6975                      "length %"PRIuSIZE, length);
6976         return OFPERR_OFPBRC_BAD_LEN;
6977     }
6978
6979     return ofputil_pull_buckets(msg, length - sizeof *ogds, version,
6980                                 &gd->buckets);
6981 }
6982
6983 /* Converts abstract group mod 'gm' into a message for OpenFlow version
6984  * 'ofp_version' and returns the message. */
6985 struct ofpbuf *
6986 ofputil_encode_group_mod(enum ofp_version ofp_version,
6987                          const struct ofputil_group_mod *gm)
6988 {
6989     struct ofpbuf *b;
6990     struct ofp11_group_mod *ogm;
6991     size_t start_ogm;
6992     size_t start_bucket;
6993     struct ofputil_bucket *bucket;
6994     struct ofp11_bucket *ob;
6995
6996     switch (ofp_version) {
6997     case OFP10_VERSION: {
6998         if (gm->command == OFPGC11_ADD) {
6999             ovs_fatal(0, "add-group needs OpenFlow 1.1 or later "
7000                          "(\'-O OpenFlow11\')");
7001         } else if (gm->command == OFPGC11_MODIFY) {
7002             ovs_fatal(0, "mod-group needs OpenFlow 1.1 or later "
7003                          "(\'-O OpenFlow11\')");
7004         } else {
7005             ovs_fatal(0, "del-groups needs OpenFlow 1.1 or later "
7006                          "(\'-O OpenFlow11\')");
7007         }
7008     }
7009
7010     case OFP11_VERSION:
7011     case OFP12_VERSION:
7012     case OFP13_VERSION:
7013     case OFP14_VERSION:
7014     case OFP15_VERSION:
7015         b = ofpraw_alloc(OFPRAW_OFPT11_GROUP_MOD, ofp_version, 0);
7016         start_ogm = ofpbuf_size(b);
7017         ofpbuf_put_zeros(b, sizeof *ogm);
7018
7019         LIST_FOR_EACH (bucket, list_node, &gm->buckets) {
7020             start_bucket = ofpbuf_size(b);
7021             ofpbuf_put_zeros(b, sizeof *ob);
7022             if (bucket->ofpacts && bucket->ofpacts_len) {
7023                 ofpacts_put_openflow_actions(bucket->ofpacts,
7024                                              bucket->ofpacts_len, b,
7025                                              ofp_version);
7026             }
7027             ob = ofpbuf_at_assert(b, start_bucket, sizeof *ob);
7028             ob->len = htons(ofpbuf_size(b) - start_bucket);;
7029             ob->weight = htons(bucket->weight);
7030             ob->watch_port = ofputil_port_to_ofp11(bucket->watch_port);
7031             ob->watch_group = htonl(bucket->watch_group);
7032         }
7033         ogm = ofpbuf_at_assert(b, start_ogm, sizeof *ogm);
7034         ogm->command = htons(gm->command);
7035         ogm->type = gm->type;
7036         ogm->group_id = htonl(gm->group_id);
7037
7038         break;
7039
7040     default:
7041         OVS_NOT_REACHED();
7042     }
7043
7044     return b;
7045 }
7046
7047 /* Converts OpenFlow group mod message 'oh' into an abstract group mod in
7048  * 'gm'.  Returns 0 if successful, otherwise an OpenFlow error code. */
7049 enum ofperr
7050 ofputil_decode_group_mod(const struct ofp_header *oh,
7051                          struct ofputil_group_mod *gm)
7052 {
7053     const struct ofp11_group_mod *ogm;
7054     struct ofpbuf msg;
7055     struct ofputil_bucket *bucket;
7056     enum ofperr err;
7057
7058     ofpbuf_use_const(&msg, oh, ntohs(oh->length));
7059     ofpraw_pull_assert(&msg);
7060
7061     ogm = ofpbuf_pull(&msg, sizeof *ogm);
7062     gm->command = ntohs(ogm->command);
7063     gm->type = ogm->type;
7064     gm->group_id = ntohl(ogm->group_id);
7065
7066     err = ofputil_pull_buckets(&msg, ofpbuf_size(&msg), oh->version, &gm->buckets);
7067     if (err) {
7068         return err;
7069     }
7070
7071     LIST_FOR_EACH (bucket, list_node, &gm->buckets) {
7072         switch (gm->type) {
7073         case OFPGT11_ALL:
7074         case OFPGT11_INDIRECT:
7075             if (ofputil_bucket_has_liveness(bucket)) {
7076                 return OFPERR_OFPGMFC_WATCH_UNSUPPORTED;
7077             }
7078             break;
7079         case OFPGT11_SELECT:
7080             break;
7081         case OFPGT11_FF:
7082             if (!ofputil_bucket_has_liveness(bucket)) {
7083                 return OFPERR_OFPGMFC_INVALID_GROUP;
7084             }
7085             break;
7086         default:
7087             OVS_NOT_REACHED();
7088         }
7089     }
7090
7091     return 0;
7092 }
7093
7094 /* Parse a queue status request message into 'oqsr'.
7095  * Returns 0 if successful, otherwise an OFPERR_* number. */
7096 enum ofperr
7097 ofputil_decode_queue_stats_request(const struct ofp_header *request,
7098                                    struct ofputil_queue_stats_request *oqsr)
7099 {
7100     switch ((enum ofp_version)request->version) {
7101     case OFP15_VERSION:
7102     case OFP14_VERSION:
7103     case OFP13_VERSION:
7104     case OFP12_VERSION:
7105     case OFP11_VERSION: {
7106         const struct ofp11_queue_stats_request *qsr11 = ofpmsg_body(request);
7107         oqsr->queue_id = ntohl(qsr11->queue_id);
7108         return ofputil_port_from_ofp11(qsr11->port_no, &oqsr->port_no);
7109     }
7110
7111     case OFP10_VERSION: {
7112         const struct ofp10_queue_stats_request *qsr10 = ofpmsg_body(request);
7113         oqsr->queue_id = ntohl(qsr10->queue_id);
7114         oqsr->port_no = u16_to_ofp(ntohs(qsr10->port_no));
7115         /* OF 1.0 uses OFPP_ALL for OFPP_ANY */
7116         if (oqsr->port_no == OFPP_ALL) {
7117             oqsr->port_no = OFPP_ANY;
7118         }
7119         return 0;
7120     }
7121
7122     default:
7123         OVS_NOT_REACHED();
7124     }
7125 }
7126
7127 /* Encode a queue statsrequest for 'oqsr', the encoded message
7128  * will be fore Open Flow version 'ofp_version'. Returns message
7129  * as a struct ofpbuf. Returns encoded message on success, NULL on error */
7130 struct ofpbuf *
7131 ofputil_encode_queue_stats_request(enum ofp_version ofp_version,
7132                                    const struct ofputil_queue_stats_request *oqsr)
7133 {
7134     struct ofpbuf *request;
7135
7136     switch (ofp_version) {
7137     case OFP11_VERSION:
7138     case OFP12_VERSION:
7139     case OFP13_VERSION:
7140     case OFP14_VERSION:
7141     case OFP15_VERSION: {
7142         struct ofp11_queue_stats_request *req;
7143         request = ofpraw_alloc(OFPRAW_OFPST11_QUEUE_REQUEST, ofp_version, 0);
7144         req = ofpbuf_put_zeros(request, sizeof *req);
7145         req->port_no = ofputil_port_to_ofp11(oqsr->port_no);
7146         req->queue_id = htonl(oqsr->queue_id);
7147         break;
7148     }
7149     case OFP10_VERSION: {
7150         struct ofp10_queue_stats_request *req;
7151         request = ofpraw_alloc(OFPRAW_OFPST10_QUEUE_REQUEST, ofp_version, 0);
7152         req = ofpbuf_put_zeros(request, sizeof *req);
7153         /* OpenFlow 1.0 needs OFPP_ALL instead of OFPP_ANY */
7154         req->port_no = htons(ofp_to_u16(oqsr->port_no == OFPP_ANY
7155                                         ? OFPP_ALL : oqsr->port_no));
7156         req->queue_id = htonl(oqsr->queue_id);
7157         break;
7158     }
7159     default:
7160         OVS_NOT_REACHED();
7161     }
7162
7163     return request;
7164 }
7165
7166 /* Returns the number of queue stats elements in OFPTYPE_QUEUE_STATS_REPLY
7167  * message 'oh'. */
7168 size_t
7169 ofputil_count_queue_stats(const struct ofp_header *oh)
7170 {
7171     struct ofputil_queue_stats qs;
7172     struct ofpbuf b;
7173     size_t n = 0;
7174
7175     ofpbuf_use_const(&b, oh, ntohs(oh->length));
7176     ofpraw_pull_assert(&b);
7177     while (!ofputil_decode_queue_stats(&qs, &b)) {
7178         n++;
7179     }
7180     return n;
7181 }
7182
7183 static enum ofperr
7184 ofputil_queue_stats_from_ofp10(struct ofputil_queue_stats *oqs,
7185                                const struct ofp10_queue_stats *qs10)
7186 {
7187     oqs->port_no = u16_to_ofp(ntohs(qs10->port_no));
7188     oqs->queue_id = ntohl(qs10->queue_id);
7189     oqs->tx_bytes = ntohll(get_32aligned_be64(&qs10->tx_bytes));
7190     oqs->tx_packets = ntohll(get_32aligned_be64(&qs10->tx_packets));
7191     oqs->tx_errors = ntohll(get_32aligned_be64(&qs10->tx_errors));
7192     oqs->duration_sec = oqs->duration_nsec = UINT32_MAX;
7193
7194     return 0;
7195 }
7196
7197 static enum ofperr
7198 ofputil_queue_stats_from_ofp11(struct ofputil_queue_stats *oqs,
7199                                const struct ofp11_queue_stats *qs11)
7200 {
7201     enum ofperr error;
7202
7203     error = ofputil_port_from_ofp11(qs11->port_no, &oqs->port_no);
7204     if (error) {
7205         return error;
7206     }
7207
7208     oqs->queue_id = ntohl(qs11->queue_id);
7209     oqs->tx_bytes = ntohll(qs11->tx_bytes);
7210     oqs->tx_packets = ntohll(qs11->tx_packets);
7211     oqs->tx_errors = ntohll(qs11->tx_errors);
7212     oqs->duration_sec = oqs->duration_nsec = UINT32_MAX;
7213
7214     return 0;
7215 }
7216
7217 static enum ofperr
7218 ofputil_queue_stats_from_ofp13(struct ofputil_queue_stats *oqs,
7219                                const struct ofp13_queue_stats *qs13)
7220 {
7221     enum ofperr error = ofputil_queue_stats_from_ofp11(oqs, &qs13->qs);
7222     if (!error) {
7223         oqs->duration_sec = ntohl(qs13->duration_sec);
7224         oqs->duration_nsec = ntohl(qs13->duration_nsec);
7225     }
7226
7227     return error;
7228 }
7229
7230 static enum ofperr
7231 ofputil_pull_ofp14_queue_stats(struct ofputil_queue_stats *oqs,
7232                                struct ofpbuf *msg)
7233 {
7234     const struct ofp14_queue_stats *qs14;
7235     size_t len;
7236
7237     qs14 = ofpbuf_try_pull(msg, sizeof *qs14);
7238     if (!qs14) {
7239         return OFPERR_OFPBRC_BAD_LEN;
7240     }
7241
7242     len = ntohs(qs14->length);
7243     if (len < sizeof *qs14 || len - sizeof *qs14 > ofpbuf_size(msg)) {
7244         return OFPERR_OFPBRC_BAD_LEN;
7245     }
7246     ofpbuf_pull(msg, len - sizeof *qs14);
7247
7248     /* No properties yet defined, so ignore them for now. */
7249
7250     return ofputil_queue_stats_from_ofp13(oqs, &qs14->qs);
7251 }
7252
7253 /* Converts an OFPST_QUEUE_STATS reply in 'msg' into an abstract
7254  * ofputil_queue_stats in 'qs'.
7255  *
7256  * Multiple OFPST_QUEUE_STATS replies can be packed into a single OpenFlow
7257  * message.  Calling this function multiple times for a single 'msg' iterates
7258  * through the replies.  The caller must initially leave 'msg''s layer pointers
7259  * null and not modify them between calls.
7260  *
7261  * Returns 0 if successful, EOF if no replies were left in this 'msg',
7262  * otherwise a positive errno value. */
7263 int
7264 ofputil_decode_queue_stats(struct ofputil_queue_stats *qs, struct ofpbuf *msg)
7265 {
7266     enum ofperr error;
7267     enum ofpraw raw;
7268
7269     error = (msg->frame
7270              ? ofpraw_decode(&raw, msg->frame)
7271              : ofpraw_pull(&raw, msg));
7272     if (error) {
7273         return error;
7274     }
7275
7276     if (!ofpbuf_size(msg)) {
7277         return EOF;
7278     } else if (raw == OFPRAW_OFPST14_QUEUE_REPLY) {
7279         return ofputil_pull_ofp14_queue_stats(qs, msg);
7280     } else if (raw == OFPRAW_OFPST13_QUEUE_REPLY) {
7281         const struct ofp13_queue_stats *qs13;
7282
7283         qs13 = ofpbuf_try_pull(msg, sizeof *qs13);
7284         if (!qs13) {
7285             goto bad_len;
7286         }
7287         return ofputil_queue_stats_from_ofp13(qs, qs13);
7288     } else if (raw == OFPRAW_OFPST11_QUEUE_REPLY) {
7289         const struct ofp11_queue_stats *qs11;
7290
7291         qs11 = ofpbuf_try_pull(msg, sizeof *qs11);
7292         if (!qs11) {
7293             goto bad_len;
7294         }
7295         return ofputil_queue_stats_from_ofp11(qs, qs11);
7296     } else if (raw == OFPRAW_OFPST10_QUEUE_REPLY) {
7297         const struct ofp10_queue_stats *qs10;
7298
7299         qs10 = ofpbuf_try_pull(msg, sizeof *qs10);
7300         if (!qs10) {
7301             goto bad_len;
7302         }
7303         return ofputil_queue_stats_from_ofp10(qs, qs10);
7304     } else {
7305         OVS_NOT_REACHED();
7306     }
7307
7308  bad_len:
7309     VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_QUEUE reply has %"PRIu32" leftover "
7310                  "bytes at end", ofpbuf_size(msg));
7311     return OFPERR_OFPBRC_BAD_LEN;
7312 }
7313
7314 static void
7315 ofputil_queue_stats_to_ofp10(const struct ofputil_queue_stats *oqs,
7316                              struct ofp10_queue_stats *qs10)
7317 {
7318     qs10->port_no = htons(ofp_to_u16(oqs->port_no));
7319     memset(qs10->pad, 0, sizeof qs10->pad);
7320     qs10->queue_id = htonl(oqs->queue_id);
7321     put_32aligned_be64(&qs10->tx_bytes, htonll(oqs->tx_bytes));
7322     put_32aligned_be64(&qs10->tx_packets, htonll(oqs->tx_packets));
7323     put_32aligned_be64(&qs10->tx_errors, htonll(oqs->tx_errors));
7324 }
7325
7326 static void
7327 ofputil_queue_stats_to_ofp11(const struct ofputil_queue_stats *oqs,
7328                              struct ofp11_queue_stats *qs11)
7329 {
7330     qs11->port_no = ofputil_port_to_ofp11(oqs->port_no);
7331     qs11->queue_id = htonl(oqs->queue_id);
7332     qs11->tx_bytes = htonll(oqs->tx_bytes);
7333     qs11->tx_packets = htonll(oqs->tx_packets);
7334     qs11->tx_errors = htonll(oqs->tx_errors);
7335 }
7336
7337 static void
7338 ofputil_queue_stats_to_ofp13(const struct ofputil_queue_stats *oqs,
7339                              struct ofp13_queue_stats *qs13)
7340 {
7341     ofputil_queue_stats_to_ofp11(oqs, &qs13->qs);
7342     if (oqs->duration_sec != UINT32_MAX) {
7343         qs13->duration_sec = htonl(oqs->duration_sec);
7344         qs13->duration_nsec = htonl(oqs->duration_nsec);
7345     } else {
7346         qs13->duration_sec = OVS_BE32_MAX;
7347         qs13->duration_nsec = OVS_BE32_MAX;
7348     }
7349 }
7350
7351 static void
7352 ofputil_queue_stats_to_ofp14(const struct ofputil_queue_stats *oqs,
7353                              struct ofp14_queue_stats *qs14)
7354 {
7355     qs14->length = htons(sizeof *qs14);
7356     memset(qs14->pad, 0, sizeof qs14->pad);
7357     ofputil_queue_stats_to_ofp13(oqs, &qs14->qs);
7358 }
7359
7360
7361 /* Encode a queue stat for 'oqs' and append it to 'replies'. */
7362 void
7363 ofputil_append_queue_stat(struct list *replies,
7364                           const struct ofputil_queue_stats *oqs)
7365 {
7366     switch (ofpmp_version(replies)) {
7367     case OFP13_VERSION: {
7368         struct ofp13_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
7369         ofputil_queue_stats_to_ofp13(oqs, reply);
7370         break;
7371     }
7372
7373     case OFP12_VERSION:
7374     case OFP11_VERSION: {
7375         struct ofp11_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
7376         ofputil_queue_stats_to_ofp11(oqs, reply);
7377         break;
7378     }
7379
7380     case OFP10_VERSION: {
7381         struct ofp10_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
7382         ofputil_queue_stats_to_ofp10(oqs, reply);
7383         break;
7384     }
7385
7386     case OFP14_VERSION:
7387     case OFP15_VERSION: {
7388         struct ofp14_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
7389         ofputil_queue_stats_to_ofp14(oqs, reply);
7390         break;
7391     }
7392
7393     default:
7394         OVS_NOT_REACHED();
7395     }
7396 }
7397
7398 enum ofperr
7399 ofputil_decode_bundle_ctrl(const struct ofp_header *oh,
7400                            struct ofputil_bundle_ctrl_msg *msg)
7401 {
7402     struct ofpbuf b;
7403     enum ofpraw raw;
7404     const struct ofp14_bundle_ctrl_msg *m;
7405
7406     ofpbuf_use_const(&b, oh, ntohs(oh->length));
7407     raw = ofpraw_pull_assert(&b);
7408     ovs_assert(raw == OFPRAW_OFPT14_BUNDLE_CONTROL);
7409
7410     m = ofpbuf_l3(&b);
7411     msg->bundle_id = ntohl(m->bundle_id);
7412     msg->type = ntohs(m->type);
7413     msg->flags = ntohs(m->flags);
7414
7415     return 0;
7416 }
7417
7418 struct ofpbuf *
7419 ofputil_encode_bundle_ctrl_reply(const struct ofp_header *oh,
7420                                  struct ofputil_bundle_ctrl_msg *msg)
7421 {
7422     struct ofpbuf *buf;
7423     struct ofp14_bundle_ctrl_msg *m;
7424
7425     buf = ofpraw_alloc_reply(OFPRAW_OFPT14_BUNDLE_CONTROL, oh, 0);
7426     m = ofpbuf_put_zeros(buf, sizeof *m);
7427
7428     m->bundle_id = htonl(msg->bundle_id);
7429     m->type = htons(msg->type);
7430     m->flags = htons(msg->flags);
7431
7432     return buf;
7433 }
7434
7435 enum ofperr
7436 ofputil_decode_bundle_add(const struct ofp_header *oh,
7437                           struct ofputil_bundle_add_msg *msg)
7438 {
7439     const struct ofp14_bundle_ctrl_msg *m;
7440     struct ofpbuf b;
7441     enum ofpraw raw;
7442     size_t inner_len;
7443
7444     ofpbuf_use_const(&b, oh, ntohs(oh->length));
7445     raw = ofpraw_pull_assert(&b);
7446     ovs_assert(raw == OFPRAW_OFPT14_BUNDLE_ADD_MESSAGE);
7447
7448     m = ofpbuf_pull(&b, sizeof *m);
7449     msg->bundle_id = ntohl(m->bundle_id);
7450     msg->flags = ntohs(m->flags);
7451
7452     msg->msg = ofpbuf_data(&b);
7453     inner_len = ntohs(msg->msg->length);
7454     if (inner_len < sizeof(struct ofp_header) || inner_len > ofpbuf_size(&b)) {
7455         return OFPERR_OFPBFC_MSG_BAD_LEN;
7456     }
7457
7458     return 0;
7459 }
7460
7461 struct ofpbuf *
7462 ofputil_encode_bundle_add(enum ofp_version ofp_version,
7463                           struct ofputil_bundle_add_msg *msg)
7464 {
7465     struct ofpbuf *request;
7466     struct ofp14_bundle_ctrl_msg *m;
7467
7468     request = ofpraw_alloc(OFPRAW_OFPT14_BUNDLE_ADD_MESSAGE, ofp_version, 0);
7469     m = ofpbuf_put_zeros(request, sizeof *m);
7470
7471     m->bundle_id = htonl(msg->bundle_id);
7472     m->flags = htons(msg->flags);
7473     ofpbuf_put(request, msg->msg, ntohs(msg->msg->length));
7474
7475     return request;
7476 }