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