9639ea49007fb9ff770edf0366f81063774ec2f2
[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 == 25);
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->l2) {
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->l2) {
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->l2;
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->l2
2684              ? ofpraw_decode(&raw, msg->l2)
2685              : ofpraw_pull(&raw, msg));
2686     if (error) {
2687         return error;
2688     }
2689     oh = msg->l2;
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->l2) {
4404         msg->l2 = ofpbuf_data(msg);
4405         ofpraw_pull_assert(msg);
4406     }
4407
4408     if (!ofpbuf_size(msg)) {
4409         return EOF;
4410     }
4411
4412     if (ofpbuf_size(msg) < sizeof *otf) {
4413         return OFPERR_OFPTFFC_BAD_LEN;
4414     }
4415
4416     otf = ofpbuf_data(msg);
4417     len = ntohs(otf->length);
4418     if (len < sizeof *otf || len % 8 || len > ofpbuf_size(msg)) {
4419         return OFPERR_OFPTFFC_BAD_LEN;
4420     }
4421     ofpbuf_pull(msg, sizeof *otf);
4422
4423     tf->table_id = otf->table_id;
4424     if (tf->table_id == OFPTT_ALL) {
4425         return OFPERR_OFPTFFC_BAD_TABLE;
4426     }
4427
4428     ovs_strlcpy(tf->name, otf->name, OFP_MAX_TABLE_NAME_LEN);
4429     tf->metadata_match = otf->metadata_match;
4430     tf->metadata_write = otf->metadata_write;
4431     tf->config = ntohl(otf->config);
4432     tf->max_entries = ntohl(otf->max_entries);
4433
4434     while (ofpbuf_size(msg) > 0) {
4435         struct ofpbuf payload;
4436         enum ofperr error;
4437         uint16_t type;
4438
4439         error = ofputil_pull_property(msg, &payload, &type);
4440         if (error) {
4441             return error;
4442         }
4443
4444         switch ((enum ofp13_table_feature_prop_type) type) {
4445         case OFPTFPT13_INSTRUCTIONS:
4446             error = parse_instruction_ids(&payload, loose,
4447                                           &tf->nonmiss.instructions);
4448             break;
4449         case OFPTFPT13_INSTRUCTIONS_MISS:
4450             error = parse_instruction_ids(&payload, loose,
4451                                           &tf->miss.instructions);
4452             break;
4453
4454         case OFPTFPT13_NEXT_TABLES:
4455             error = parse_table_features_next_table(&payload,
4456                                                     tf->nonmiss.next);
4457             break;
4458         case OFPTFPT13_NEXT_TABLES_MISS:
4459             error = parse_table_features_next_table(&payload, tf->miss.next);
4460             break;
4461
4462         case OFPTFPT13_WRITE_ACTIONS:
4463             error = parse_table_ids(&payload, &tf->nonmiss.write.actions);
4464             break;
4465         case OFPTFPT13_WRITE_ACTIONS_MISS:
4466             error = parse_table_ids(&payload, &tf->miss.write.actions);
4467             break;
4468
4469         case OFPTFPT13_APPLY_ACTIONS:
4470             error = parse_table_ids(&payload, &tf->nonmiss.apply.actions);
4471             break;
4472         case OFPTFPT13_APPLY_ACTIONS_MISS:
4473             error = parse_table_ids(&payload, &tf->miss.apply.actions);
4474             break;
4475
4476         case OFPTFPT13_MATCH:
4477             error = parse_oxms(&payload, loose, &tf->match, &tf->mask);
4478             break;
4479         case OFPTFPT13_WILDCARDS:
4480             error = parse_oxms(&payload, loose, &tf->wildcard, NULL);
4481             break;
4482
4483         case OFPTFPT13_WRITE_SETFIELD:
4484             error = parse_oxms(&payload, loose,
4485                                &tf->nonmiss.write.set_fields, NULL);
4486             break;
4487         case OFPTFPT13_WRITE_SETFIELD_MISS:
4488             error = parse_oxms(&payload, loose,
4489                                &tf->miss.write.set_fields, NULL);
4490             break;
4491         case OFPTFPT13_APPLY_SETFIELD:
4492             error = parse_oxms(&payload, loose,
4493                                &tf->nonmiss.apply.set_fields, NULL);
4494             break;
4495         case OFPTFPT13_APPLY_SETFIELD_MISS:
4496             error = parse_oxms(&payload, loose,
4497                                &tf->miss.apply.set_fields, NULL);
4498             break;
4499
4500         case OFPTFPT13_EXPERIMENTER:
4501         case OFPTFPT13_EXPERIMENTER_MISS:
4502             log_property(loose,
4503                          "unknown table features experimenter property");
4504             error = loose ? 0 : OFPERR_OFPTFFC_BAD_TYPE;
4505             break;
4506         }
4507         if (error) {
4508             return error;
4509         }
4510     }
4511
4512     /* Fix inconsistencies:
4513      *
4514      *     - Turn off 'mask' and 'wildcard' bits that are not in 'match',
4515      *       because a field must be matchable to be masked or wildcarded.
4516      *
4517      *     - Turn on 'wildcard' bits that are set in 'mask', because a field
4518      *       that is arbitrarily maskable can be wildcarded entirely. */
4519     tf->mask &= tf->match;
4520     tf->wildcard &= tf->match;
4521
4522     tf->wildcard |= tf->mask;
4523
4524     return 0;
4525 }
4526
4527 /* Encodes and returns a request to obtain the table features of a switch.
4528  * The message is encoded for OpenFlow version 'ofp_version'. */
4529 struct ofpbuf *
4530 ofputil_encode_table_features_request(enum ofp_version ofp_version)
4531 {
4532     struct ofpbuf *request = NULL;
4533
4534     switch (ofp_version) {
4535     case OFP10_VERSION:
4536     case OFP11_VERSION:
4537     case OFP12_VERSION:
4538         ovs_fatal(0, "dump-table-features needs OpenFlow 1.3 or later "
4539                      "(\'-O OpenFlow13\')");
4540     case OFP13_VERSION:
4541     case OFP14_VERSION:
4542         request = ofpraw_alloc(OFPRAW_OFPST13_TABLE_FEATURES_REQUEST,
4543                                ofp_version, 0);
4544         break;
4545     default:
4546         OVS_NOT_REACHED();
4547     }
4548
4549     return request;
4550 }
4551
4552 /* ofputil_table_mod */
4553
4554 /* Decodes the OpenFlow "table mod" message in '*oh' into an abstract form in
4555  * '*pm'.  Returns 0 if successful, otherwise an OFPERR_* value. */
4556 enum ofperr
4557 ofputil_decode_table_mod(const struct ofp_header *oh,
4558                          struct ofputil_table_mod *pm)
4559 {
4560     enum ofpraw raw;
4561     struct ofpbuf b;
4562
4563     ofpbuf_use_const(&b, oh, ntohs(oh->length));
4564     raw = ofpraw_pull_assert(&b);
4565
4566     if (raw == OFPRAW_OFPT11_TABLE_MOD) {
4567         const struct ofp11_table_mod *otm = ofpbuf_data(&b);
4568
4569         pm->table_id = otm->table_id;
4570         pm->config = ntohl(otm->config);
4571     } else {
4572         return OFPERR_OFPBRC_BAD_TYPE;
4573     }
4574
4575     return 0;
4576 }
4577
4578 /* Converts the abstract form of a "table mod" message in '*pm' into an OpenFlow
4579  * message suitable for 'protocol', and returns that encoded form in a buffer
4580  * owned by the caller. */
4581 struct ofpbuf *
4582 ofputil_encode_table_mod(const struct ofputil_table_mod *pm,
4583                         enum ofputil_protocol protocol)
4584 {
4585     enum ofp_version ofp_version = ofputil_protocol_to_ofp_version(protocol);
4586     struct ofpbuf *b;
4587
4588     switch (ofp_version) {
4589     case OFP10_VERSION: {
4590         ovs_fatal(0, "table mod needs OpenFlow 1.1 or later "
4591                      "(\'-O OpenFlow11\')");
4592         break;
4593     }
4594     case OFP11_VERSION:
4595     case OFP12_VERSION:
4596     case OFP13_VERSION: {
4597         struct ofp11_table_mod *otm;
4598
4599         b = ofpraw_alloc(OFPRAW_OFPT11_TABLE_MOD, ofp_version, 0);
4600         otm = ofpbuf_put_zeros(b, sizeof *otm);
4601         otm->table_id = pm->table_id;
4602         otm->config = htonl(pm->config);
4603         break;
4604     }
4605     case OFP14_VERSION:
4606         OVS_NOT_REACHED();
4607         break;
4608     default:
4609         OVS_NOT_REACHED();
4610     }
4611
4612     return b;
4613 }
4614 \f
4615 /* ofputil_role_request */
4616
4617 /* Decodes the OpenFlow "role request" or "role reply" message in '*oh' into
4618  * an abstract form in '*rr'.  Returns 0 if successful, otherwise an
4619  * OFPERR_* value. */
4620 enum ofperr
4621 ofputil_decode_role_message(const struct ofp_header *oh,
4622                             struct ofputil_role_request *rr)
4623 {
4624     struct ofpbuf b;
4625     enum ofpraw raw;
4626
4627     ofpbuf_use_const(&b, oh, ntohs(oh->length));
4628     raw = ofpraw_pull_assert(&b);
4629
4630     if (raw == OFPRAW_OFPT12_ROLE_REQUEST ||
4631         raw == OFPRAW_OFPT12_ROLE_REPLY) {
4632         const struct ofp12_role_request *orr = ofpbuf_l3(&b);
4633
4634         if (orr->role != htonl(OFPCR12_ROLE_NOCHANGE) &&
4635             orr->role != htonl(OFPCR12_ROLE_EQUAL) &&
4636             orr->role != htonl(OFPCR12_ROLE_MASTER) &&
4637             orr->role != htonl(OFPCR12_ROLE_SLAVE)) {
4638             return OFPERR_OFPRRFC_BAD_ROLE;
4639         }
4640
4641         rr->role = ntohl(orr->role);
4642         if (raw == OFPRAW_OFPT12_ROLE_REQUEST
4643             ? orr->role == htonl(OFPCR12_ROLE_NOCHANGE)
4644             : orr->generation_id == OVS_BE64_MAX) {
4645             rr->have_generation_id = false;
4646             rr->generation_id = 0;
4647         } else {
4648             rr->have_generation_id = true;
4649             rr->generation_id = ntohll(orr->generation_id);
4650         }
4651     } else if (raw == OFPRAW_NXT_ROLE_REQUEST ||
4652                raw == OFPRAW_NXT_ROLE_REPLY) {
4653         const struct nx_role_request *nrr = ofpbuf_l3(&b);
4654
4655         BUILD_ASSERT(NX_ROLE_OTHER + 1 == OFPCR12_ROLE_EQUAL);
4656         BUILD_ASSERT(NX_ROLE_MASTER + 1 == OFPCR12_ROLE_MASTER);
4657         BUILD_ASSERT(NX_ROLE_SLAVE + 1 == OFPCR12_ROLE_SLAVE);
4658
4659         if (nrr->role != htonl(NX_ROLE_OTHER) &&
4660             nrr->role != htonl(NX_ROLE_MASTER) &&
4661             nrr->role != htonl(NX_ROLE_SLAVE)) {
4662             return OFPERR_OFPRRFC_BAD_ROLE;
4663         }
4664
4665         rr->role = ntohl(nrr->role) + 1;
4666         rr->have_generation_id = false;
4667         rr->generation_id = 0;
4668     } else {
4669         OVS_NOT_REACHED();
4670     }
4671
4672     return 0;
4673 }
4674
4675 /* Returns an encoded form of a role reply suitable for the "request" in a
4676  * buffer owned by the caller. */
4677 struct ofpbuf *
4678 ofputil_encode_role_reply(const struct ofp_header *request,
4679                           const struct ofputil_role_request *rr)
4680 {
4681     struct ofpbuf *buf;
4682     enum ofpraw raw;
4683
4684     raw = ofpraw_decode_assert(request);
4685     if (raw == OFPRAW_OFPT12_ROLE_REQUEST) {
4686         struct ofp12_role_request *orr;
4687
4688         buf = ofpraw_alloc_reply(OFPRAW_OFPT12_ROLE_REPLY, request, 0);
4689         orr = ofpbuf_put_zeros(buf, sizeof *orr);
4690
4691         orr->role = htonl(rr->role);
4692         orr->generation_id = htonll(rr->have_generation_id
4693                                     ? rr->generation_id
4694                                     : UINT64_MAX);
4695     } else if (raw == OFPRAW_NXT_ROLE_REQUEST) {
4696         struct nx_role_request *nrr;
4697
4698         BUILD_ASSERT(NX_ROLE_OTHER == OFPCR12_ROLE_EQUAL - 1);
4699         BUILD_ASSERT(NX_ROLE_MASTER == OFPCR12_ROLE_MASTER - 1);
4700         BUILD_ASSERT(NX_ROLE_SLAVE == OFPCR12_ROLE_SLAVE - 1);
4701
4702         buf = ofpraw_alloc_reply(OFPRAW_NXT_ROLE_REPLY, request, 0);
4703         nrr = ofpbuf_put_zeros(buf, sizeof *nrr);
4704         nrr->role = htonl(rr->role - 1);
4705     } else {
4706         OVS_NOT_REACHED();
4707     }
4708
4709     return buf;
4710 }
4711 \f
4712 struct ofpbuf *
4713 ofputil_encode_role_status(const struct ofputil_role_status *status,
4714                            enum ofputil_protocol protocol)
4715 {
4716     struct ofpbuf *buf;
4717     enum ofp_version version;
4718     struct ofp14_role_status *rstatus;
4719
4720     version = ofputil_protocol_to_ofp_version(protocol);
4721     buf = ofpraw_alloc_xid(OFPRAW_OFPT14_ROLE_STATUS, version, htonl(0), 0);
4722     rstatus = ofpbuf_put_zeros(buf, sizeof *rstatus);
4723     rstatus->role = htonl(status->role);
4724     rstatus->reason = status->reason;
4725     rstatus->generation_id = htonll(status->generation_id);
4726
4727     return buf;
4728 }
4729
4730 enum ofperr
4731 ofputil_decode_role_status(const struct ofp_header *oh,
4732                            struct ofputil_role_status *rs)
4733 {
4734     struct ofpbuf b;
4735     enum ofpraw raw;
4736     const struct ofp14_role_status *r;
4737
4738     ofpbuf_use_const(&b, oh, ntohs(oh->length));
4739     raw = ofpraw_pull_assert(&b);
4740     ovs_assert(raw == OFPRAW_OFPT14_ROLE_STATUS);
4741
4742     r = ofpbuf_l3(&b);
4743     if (r->role != htonl(OFPCR12_ROLE_NOCHANGE) &&
4744         r->role != htonl(OFPCR12_ROLE_EQUAL) &&
4745         r->role != htonl(OFPCR12_ROLE_MASTER) &&
4746         r->role != htonl(OFPCR12_ROLE_SLAVE)) {
4747         return OFPERR_OFPRRFC_BAD_ROLE;
4748     }
4749
4750     rs->role = ntohl(r->role);
4751     rs->generation_id = ntohll(r->generation_id);
4752     rs->reason = r->reason;
4753
4754     return 0;
4755 }
4756
4757 /* Table stats. */
4758
4759 static void
4760 ofputil_put_ofp10_table_stats(const struct ofp12_table_stats *in,
4761                               struct ofpbuf *buf)
4762 {
4763     struct wc_map {
4764         enum ofp10_flow_wildcards wc10;
4765         enum oxm12_ofb_match_fields mf12;
4766     };
4767
4768     static const struct wc_map wc_map[] = {
4769         { OFPFW10_IN_PORT,     OFPXMT12_OFB_IN_PORT },
4770         { OFPFW10_DL_VLAN,     OFPXMT12_OFB_VLAN_VID },
4771         { OFPFW10_DL_SRC,      OFPXMT12_OFB_ETH_SRC },
4772         { OFPFW10_DL_DST,      OFPXMT12_OFB_ETH_DST},
4773         { OFPFW10_DL_TYPE,     OFPXMT12_OFB_ETH_TYPE },
4774         { OFPFW10_NW_PROTO,    OFPXMT12_OFB_IP_PROTO },
4775         { OFPFW10_TP_SRC,      OFPXMT12_OFB_TCP_SRC },
4776         { OFPFW10_TP_DST,      OFPXMT12_OFB_TCP_DST },
4777         { OFPFW10_NW_SRC_MASK, OFPXMT12_OFB_IPV4_SRC },
4778         { OFPFW10_NW_DST_MASK, OFPXMT12_OFB_IPV4_DST },
4779         { OFPFW10_DL_VLAN_PCP, OFPXMT12_OFB_VLAN_PCP },
4780         { OFPFW10_NW_TOS,      OFPXMT12_OFB_IP_DSCP },
4781     };
4782
4783     struct ofp10_table_stats *out;
4784     const struct wc_map *p;
4785
4786     out = ofpbuf_put_zeros(buf, sizeof *out);
4787     out->table_id = in->table_id;
4788     ovs_strlcpy(out->name, in->name, sizeof out->name);
4789     out->wildcards = 0;
4790     for (p = wc_map; p < &wc_map[ARRAY_SIZE(wc_map)]; p++) {
4791         if (in->wildcards & htonll(1ULL << p->mf12)) {
4792             out->wildcards |= htonl(p->wc10);
4793         }
4794     }
4795     out->max_entries = in->max_entries;
4796     out->active_count = in->active_count;
4797     put_32aligned_be64(&out->lookup_count, in->lookup_count);
4798     put_32aligned_be64(&out->matched_count, in->matched_count);
4799 }
4800
4801 static ovs_be32
4802 oxm12_to_ofp11_flow_match_fields(ovs_be64 oxm12)
4803 {
4804     struct map {
4805         enum ofp11_flow_match_fields fmf11;
4806         enum oxm12_ofb_match_fields mf12;
4807     };
4808
4809     static const struct map map[] = {
4810         { OFPFMF11_IN_PORT,     OFPXMT12_OFB_IN_PORT },
4811         { OFPFMF11_DL_VLAN,     OFPXMT12_OFB_VLAN_VID },
4812         { OFPFMF11_DL_VLAN_PCP, OFPXMT12_OFB_VLAN_PCP },
4813         { OFPFMF11_DL_TYPE,     OFPXMT12_OFB_ETH_TYPE },
4814         { OFPFMF11_NW_TOS,      OFPXMT12_OFB_IP_DSCP },
4815         { OFPFMF11_NW_PROTO,    OFPXMT12_OFB_IP_PROTO },
4816         { OFPFMF11_TP_SRC,      OFPXMT12_OFB_TCP_SRC },
4817         { OFPFMF11_TP_DST,      OFPXMT12_OFB_TCP_DST },
4818         { OFPFMF11_MPLS_LABEL,  OFPXMT12_OFB_MPLS_LABEL },
4819         { OFPFMF11_MPLS_TC,     OFPXMT12_OFB_MPLS_TC },
4820         /* I don't know what OFPFMF11_TYPE means. */
4821         { OFPFMF11_DL_SRC,      OFPXMT12_OFB_ETH_SRC },
4822         { OFPFMF11_DL_DST,      OFPXMT12_OFB_ETH_DST },
4823         { OFPFMF11_NW_SRC,      OFPXMT12_OFB_IPV4_SRC },
4824         { OFPFMF11_NW_DST,      OFPXMT12_OFB_IPV4_DST },
4825         { OFPFMF11_METADATA,    OFPXMT12_OFB_METADATA },
4826     };
4827
4828     const struct map *p;
4829     uint32_t fmf11;
4830
4831     fmf11 = 0;
4832     for (p = map; p < &map[ARRAY_SIZE(map)]; p++) {
4833         if (oxm12 & htonll(1ULL << p->mf12)) {
4834             fmf11 |= p->fmf11;
4835         }
4836     }
4837     return htonl(fmf11);
4838 }
4839
4840 static void
4841 ofputil_put_ofp11_table_stats(const struct ofp12_table_stats *in,
4842                               struct ofpbuf *buf)
4843 {
4844     struct ofp11_table_stats *out;
4845
4846     out = ofpbuf_put_zeros(buf, sizeof *out);
4847     out->table_id = in->table_id;
4848     ovs_strlcpy(out->name, in->name, sizeof out->name);
4849     out->wildcards = oxm12_to_ofp11_flow_match_fields(in->wildcards);
4850     out->match = oxm12_to_ofp11_flow_match_fields(in->match);
4851     out->instructions = in->instructions;
4852     out->write_actions = in->write_actions;
4853     out->apply_actions = in->apply_actions;
4854     out->config = in->config;
4855     out->max_entries = in->max_entries;
4856     out->active_count = in->active_count;
4857     out->lookup_count = in->lookup_count;
4858     out->matched_count = in->matched_count;
4859 }
4860
4861 static void
4862 ofputil_put_ofp12_table_stats(const struct ofp12_table_stats *in,
4863                               struct ofpbuf *buf)
4864 {
4865     struct ofp12_table_stats *out = ofpbuf_put(buf, in, sizeof *in);
4866
4867     /* Trim off OF1.3-only capabilities. */
4868     out->match &= htonll(OFPXMT12_MASK);
4869     out->wildcards &= htonll(OFPXMT12_MASK);
4870     out->write_setfields &= htonll(OFPXMT12_MASK);
4871     out->apply_setfields &= htonll(OFPXMT12_MASK);
4872 }
4873
4874 static void
4875 ofputil_put_ofp13_table_stats(const struct ofp12_table_stats *in,
4876                               struct ofpbuf *buf)
4877 {
4878     struct ofp13_table_stats *out;
4879
4880     /* OF 1.3 splits table features off the ofp_table_stats,
4881      * so there is not much here. */
4882
4883     out = ofpbuf_put_uninit(buf, sizeof *out);
4884     out->table_id = in->table_id;
4885     out->active_count = in->active_count;
4886     out->lookup_count = in->lookup_count;
4887     out->matched_count = in->matched_count;
4888 }
4889
4890 struct ofpbuf *
4891 ofputil_encode_table_stats_reply(const struct ofp12_table_stats stats[], int n,
4892                                  const struct ofp_header *request)
4893 {
4894     struct ofpbuf *reply;
4895     int i;
4896
4897     reply = ofpraw_alloc_stats_reply(request, n * sizeof *stats);
4898
4899     for (i = 0; i < n; i++) {
4900         switch ((enum ofp_version) request->version) {
4901         case OFP10_VERSION:
4902             ofputil_put_ofp10_table_stats(&stats[i], reply);
4903             break;
4904
4905         case OFP11_VERSION:
4906             ofputil_put_ofp11_table_stats(&stats[i], reply);
4907             break;
4908
4909         case OFP12_VERSION:
4910             ofputil_put_ofp12_table_stats(&stats[i], reply);
4911             break;
4912
4913         case OFP13_VERSION:
4914         case OFP14_VERSION:
4915             ofputil_put_ofp13_table_stats(&stats[i], reply);
4916             break;
4917
4918         default:
4919             OVS_NOT_REACHED();
4920         }
4921     }
4922
4923     return reply;
4924 }
4925 \f
4926 /* ofputil_flow_monitor_request */
4927
4928 /* Converts an NXST_FLOW_MONITOR request in 'msg' into an abstract
4929  * ofputil_flow_monitor_request in 'rq'.
4930  *
4931  * Multiple NXST_FLOW_MONITOR requests can be packed into a single OpenFlow
4932  * message.  Calling this function multiple times for a single 'msg' iterates
4933  * through the requests.  The caller must initially leave 'msg''s layer
4934  * pointers null and not modify them between calls.
4935  *
4936  * Returns 0 if successful, EOF if no requests were left in this 'msg',
4937  * otherwise an OFPERR_* value. */
4938 int
4939 ofputil_decode_flow_monitor_request(struct ofputil_flow_monitor_request *rq,
4940                                     struct ofpbuf *msg)
4941 {
4942     struct nx_flow_monitor_request *nfmr;
4943     uint16_t flags;
4944
4945     if (!msg->l2) {
4946         msg->l2 = ofpbuf_data(msg);
4947         ofpraw_pull_assert(msg);
4948     }
4949
4950     if (!ofpbuf_size(msg)) {
4951         return EOF;
4952     }
4953
4954     nfmr = ofpbuf_try_pull(msg, sizeof *nfmr);
4955     if (!nfmr) {
4956         VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR request has %"PRIu32" "
4957                      "leftover bytes at end", ofpbuf_size(msg));
4958         return OFPERR_OFPBRC_BAD_LEN;
4959     }
4960
4961     flags = ntohs(nfmr->flags);
4962     if (!(flags & (NXFMF_ADD | NXFMF_DELETE | NXFMF_MODIFY))
4963         || flags & ~(NXFMF_INITIAL | NXFMF_ADD | NXFMF_DELETE
4964                      | NXFMF_MODIFY | NXFMF_ACTIONS | NXFMF_OWN)) {
4965         VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR has bad flags %#"PRIx16,
4966                      flags);
4967         return OFPERR_NXBRC_FM_BAD_FLAGS;
4968     }
4969
4970     if (!is_all_zeros(nfmr->zeros, sizeof nfmr->zeros)) {
4971         return OFPERR_NXBRC_MUST_BE_ZERO;
4972     }
4973
4974     rq->id = ntohl(nfmr->id);
4975     rq->flags = flags;
4976     rq->out_port = u16_to_ofp(ntohs(nfmr->out_port));
4977     rq->table_id = nfmr->table_id;
4978
4979     return nx_pull_match(msg, ntohs(nfmr->match_len), &rq->match, NULL, NULL);
4980 }
4981
4982 void
4983 ofputil_append_flow_monitor_request(
4984     const struct ofputil_flow_monitor_request *rq, struct ofpbuf *msg)
4985 {
4986     struct nx_flow_monitor_request *nfmr;
4987     size_t start_ofs;
4988     int match_len;
4989
4990     if (!ofpbuf_size(msg)) {
4991         ofpraw_put(OFPRAW_NXST_FLOW_MONITOR_REQUEST, OFP10_VERSION, msg);
4992     }
4993
4994     start_ofs = ofpbuf_size(msg);
4995     ofpbuf_put_zeros(msg, sizeof *nfmr);
4996     match_len = nx_put_match(msg, &rq->match, htonll(0), htonll(0));
4997
4998     nfmr = ofpbuf_at_assert(msg, start_ofs, sizeof *nfmr);
4999     nfmr->id = htonl(rq->id);
5000     nfmr->flags = htons(rq->flags);
5001     nfmr->out_port = htons(ofp_to_u16(rq->out_port));
5002     nfmr->match_len = htons(match_len);
5003     nfmr->table_id = rq->table_id;
5004 }
5005
5006 /* Converts an NXST_FLOW_MONITOR reply (also known as a flow update) in 'msg'
5007  * into an abstract ofputil_flow_update in 'update'.  The caller must have
5008  * initialized update->match to point to space allocated for a match.
5009  *
5010  * Uses 'ofpacts' to store the abstract OFPACT_* version of the update's
5011  * actions (except for NXFME_ABBREV, which never includes actions).  The caller
5012  * must initialize 'ofpacts' and retains ownership of it.  'update->ofpacts'
5013  * will point into the 'ofpacts' buffer.
5014  *
5015  * Multiple flow updates can be packed into a single OpenFlow message.  Calling
5016  * this function multiple times for a single 'msg' iterates through the
5017  * updates.  The caller must initially leave 'msg''s layer pointers null and
5018  * not modify them between calls.
5019  *
5020  * Returns 0 if successful, EOF if no updates were left in this 'msg',
5021  * otherwise an OFPERR_* value. */
5022 int
5023 ofputil_decode_flow_update(struct ofputil_flow_update *update,
5024                            struct ofpbuf *msg, struct ofpbuf *ofpacts)
5025 {
5026     struct nx_flow_update_header *nfuh;
5027     unsigned int length;
5028     struct ofp_header *oh;
5029
5030     if (!msg->l2) {
5031         msg->l2 = ofpbuf_data(msg);
5032         ofpraw_pull_assert(msg);
5033     }
5034
5035     if (!ofpbuf_size(msg)) {
5036         return EOF;
5037     }
5038
5039     if (ofpbuf_size(msg) < sizeof(struct nx_flow_update_header)) {
5040         goto bad_len;
5041     }
5042
5043     oh = msg->l2;
5044
5045     nfuh = ofpbuf_data(msg);
5046     update->event = ntohs(nfuh->event);
5047     length = ntohs(nfuh->length);
5048     if (length > ofpbuf_size(msg) || length % 8) {
5049         goto bad_len;
5050     }
5051
5052     if (update->event == NXFME_ABBREV) {
5053         struct nx_flow_update_abbrev *nfua;
5054
5055         if (length != sizeof *nfua) {
5056             goto bad_len;
5057         }
5058
5059         nfua = ofpbuf_pull(msg, sizeof *nfua);
5060         update->xid = nfua->xid;
5061         return 0;
5062     } else if (update->event == NXFME_ADDED
5063                || update->event == NXFME_DELETED
5064                || update->event == NXFME_MODIFIED) {
5065         struct nx_flow_update_full *nfuf;
5066         unsigned int actions_len;
5067         unsigned int match_len;
5068         enum ofperr error;
5069
5070         if (length < sizeof *nfuf) {
5071             goto bad_len;
5072         }
5073
5074         nfuf = ofpbuf_pull(msg, sizeof *nfuf);
5075         match_len = ntohs(nfuf->match_len);
5076         if (sizeof *nfuf + match_len > length) {
5077             goto bad_len;
5078         }
5079
5080         update->reason = ntohs(nfuf->reason);
5081         update->idle_timeout = ntohs(nfuf->idle_timeout);
5082         update->hard_timeout = ntohs(nfuf->hard_timeout);
5083         update->table_id = nfuf->table_id;
5084         update->cookie = nfuf->cookie;
5085         update->priority = ntohs(nfuf->priority);
5086
5087         error = nx_pull_match(msg, match_len, update->match, NULL, NULL);
5088         if (error) {
5089             return error;
5090         }
5091
5092         actions_len = length - sizeof *nfuf - ROUND_UP(match_len, 8);
5093         error = ofpacts_pull_openflow_actions(msg, actions_len, oh->version,
5094                                               ofpacts);
5095         if (error) {
5096             return error;
5097         }
5098
5099         update->ofpacts = ofpbuf_data(ofpacts);
5100         update->ofpacts_len = ofpbuf_size(ofpacts);
5101         return 0;
5102     } else {
5103         VLOG_WARN_RL(&bad_ofmsg_rl,
5104                      "NXST_FLOW_MONITOR reply has bad event %"PRIu16,
5105                      ntohs(nfuh->event));
5106         return OFPERR_NXBRC_FM_BAD_EVENT;
5107     }
5108
5109 bad_len:
5110     VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR reply has %"PRIu32" "
5111                  "leftover bytes at end", ofpbuf_size(msg));
5112     return OFPERR_OFPBRC_BAD_LEN;
5113 }
5114
5115 uint32_t
5116 ofputil_decode_flow_monitor_cancel(const struct ofp_header *oh)
5117 {
5118     const struct nx_flow_monitor_cancel *cancel = ofpmsg_body(oh);
5119
5120     return ntohl(cancel->id);
5121 }
5122
5123 struct ofpbuf *
5124 ofputil_encode_flow_monitor_cancel(uint32_t id)
5125 {
5126     struct nx_flow_monitor_cancel *nfmc;
5127     struct ofpbuf *msg;
5128
5129     msg = ofpraw_alloc(OFPRAW_NXT_FLOW_MONITOR_CANCEL, OFP10_VERSION, 0);
5130     nfmc = ofpbuf_put_uninit(msg, sizeof *nfmc);
5131     nfmc->id = htonl(id);
5132     return msg;
5133 }
5134
5135 void
5136 ofputil_start_flow_update(struct list *replies)
5137 {
5138     struct ofpbuf *msg;
5139
5140     msg = ofpraw_alloc_xid(OFPRAW_NXST_FLOW_MONITOR_REPLY, OFP10_VERSION,
5141                            htonl(0), 1024);
5142
5143     list_init(replies);
5144     list_push_back(replies, &msg->list_node);
5145 }
5146
5147 void
5148 ofputil_append_flow_update(const struct ofputil_flow_update *update,
5149                            struct list *replies)
5150 {
5151     struct nx_flow_update_header *nfuh;
5152     struct ofpbuf *msg;
5153     size_t start_ofs;
5154     enum ofp_version version;
5155
5156     msg = ofpbuf_from_list(list_back(replies));
5157     start_ofs = ofpbuf_size(msg);
5158     version = ((struct ofp_header *)msg->l2)->version;
5159
5160     if (update->event == NXFME_ABBREV) {
5161         struct nx_flow_update_abbrev *nfua;
5162
5163         nfua = ofpbuf_put_zeros(msg, sizeof *nfua);
5164         nfua->xid = update->xid;
5165     } else {
5166         struct nx_flow_update_full *nfuf;
5167         int match_len;
5168
5169         ofpbuf_put_zeros(msg, sizeof *nfuf);
5170         match_len = nx_put_match(msg, update->match, htonll(0), htonll(0));
5171         ofpacts_put_openflow_actions(update->ofpacts, update->ofpacts_len, msg,
5172                                      version);
5173         nfuf = ofpbuf_at_assert(msg, start_ofs, sizeof *nfuf);
5174         nfuf->reason = htons(update->reason);
5175         nfuf->priority = htons(update->priority);
5176         nfuf->idle_timeout = htons(update->idle_timeout);
5177         nfuf->hard_timeout = htons(update->hard_timeout);
5178         nfuf->match_len = htons(match_len);
5179         nfuf->table_id = update->table_id;
5180         nfuf->cookie = update->cookie;
5181     }
5182
5183     nfuh = ofpbuf_at_assert(msg, start_ofs, sizeof *nfuh);
5184     nfuh->length = htons(ofpbuf_size(msg) - start_ofs);
5185     nfuh->event = htons(update->event);
5186
5187     ofpmp_postappend(replies, start_ofs);
5188 }
5189 \f
5190 struct ofpbuf *
5191 ofputil_encode_packet_out(const struct ofputil_packet_out *po,
5192                           enum ofputil_protocol protocol)
5193 {
5194     enum ofp_version ofp_version = ofputil_protocol_to_ofp_version(protocol);
5195     struct ofpbuf *msg;
5196     size_t size;
5197
5198     size = po->ofpacts_len;
5199     if (po->buffer_id == UINT32_MAX) {
5200         size += po->packet_len;
5201     }
5202
5203     switch (ofp_version) {
5204     case OFP10_VERSION: {
5205         struct ofp10_packet_out *opo;
5206         size_t actions_ofs;
5207
5208         msg = ofpraw_alloc(OFPRAW_OFPT10_PACKET_OUT, OFP10_VERSION, size);
5209         ofpbuf_put_zeros(msg, sizeof *opo);
5210         actions_ofs = ofpbuf_size(msg);
5211         ofpacts_put_openflow_actions(po->ofpacts, po->ofpacts_len, msg,
5212                                      ofp_version);
5213
5214         opo = ofpbuf_l3(msg);
5215         opo->buffer_id = htonl(po->buffer_id);
5216         opo->in_port = htons(ofp_to_u16(po->in_port));
5217         opo->actions_len = htons(ofpbuf_size(msg) - actions_ofs);
5218         break;
5219     }
5220
5221     case OFP11_VERSION:
5222     case OFP12_VERSION:
5223     case OFP13_VERSION:
5224     case OFP14_VERSION:{
5225         struct ofp11_packet_out *opo;
5226         size_t len;
5227
5228         msg = ofpraw_alloc(OFPRAW_OFPT11_PACKET_OUT, ofp_version, size);
5229         ofpbuf_put_zeros(msg, sizeof *opo);
5230         len = ofpacts_put_openflow_actions(po->ofpacts, po->ofpacts_len, msg,
5231                                            ofp_version);
5232         opo = ofpbuf_l3(msg);
5233         opo->buffer_id = htonl(po->buffer_id);
5234         opo->in_port = ofputil_port_to_ofp11(po->in_port);
5235         opo->actions_len = htons(len);
5236         break;
5237     }
5238
5239     default:
5240         OVS_NOT_REACHED();
5241     }
5242
5243     if (po->buffer_id == UINT32_MAX) {
5244         ofpbuf_put(msg, po->packet, po->packet_len);
5245     }
5246
5247     ofpmsg_update_length(msg);
5248
5249     return msg;
5250 }
5251 \f
5252 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
5253 struct ofpbuf *
5254 make_echo_request(enum ofp_version ofp_version)
5255 {
5256     return ofpraw_alloc_xid(OFPRAW_OFPT_ECHO_REQUEST, ofp_version,
5257                             htonl(0), 0);
5258 }
5259
5260 /* Creates and returns an OFPT_ECHO_REPLY message matching the
5261  * OFPT_ECHO_REQUEST message in 'rq'. */
5262 struct ofpbuf *
5263 make_echo_reply(const struct ofp_header *rq)
5264 {
5265     struct ofpbuf rq_buf;
5266     struct ofpbuf *reply;
5267
5268     ofpbuf_use_const(&rq_buf, rq, ntohs(rq->length));
5269     ofpraw_pull_assert(&rq_buf);
5270
5271     reply = ofpraw_alloc_reply(OFPRAW_OFPT_ECHO_REPLY, rq, ofpbuf_size(&rq_buf));
5272     ofpbuf_put(reply, ofpbuf_data(&rq_buf), ofpbuf_size(&rq_buf));
5273     return reply;
5274 }
5275
5276 struct ofpbuf *
5277 ofputil_encode_barrier_request(enum ofp_version ofp_version)
5278 {
5279     enum ofpraw type;
5280
5281     switch (ofp_version) {
5282     case OFP14_VERSION:
5283     case OFP13_VERSION:
5284     case OFP12_VERSION:
5285     case OFP11_VERSION:
5286         type = OFPRAW_OFPT11_BARRIER_REQUEST;
5287         break;
5288
5289     case OFP10_VERSION:
5290         type = OFPRAW_OFPT10_BARRIER_REQUEST;
5291         break;
5292
5293     default:
5294         OVS_NOT_REACHED();
5295     }
5296
5297     return ofpraw_alloc(type, ofp_version, 0);
5298 }
5299
5300 const char *
5301 ofputil_frag_handling_to_string(enum ofp_config_flags flags)
5302 {
5303     switch (flags & OFPC_FRAG_MASK) {
5304     case OFPC_FRAG_NORMAL:   return "normal";
5305     case OFPC_FRAG_DROP:     return "drop";
5306     case OFPC_FRAG_REASM:    return "reassemble";
5307     case OFPC_FRAG_NX_MATCH: return "nx-match";
5308     }
5309
5310     OVS_NOT_REACHED();
5311 }
5312
5313 bool
5314 ofputil_frag_handling_from_string(const char *s, enum ofp_config_flags *flags)
5315 {
5316     if (!strcasecmp(s, "normal")) {
5317         *flags = OFPC_FRAG_NORMAL;
5318     } else if (!strcasecmp(s, "drop")) {
5319         *flags = OFPC_FRAG_DROP;
5320     } else if (!strcasecmp(s, "reassemble")) {
5321         *flags = OFPC_FRAG_REASM;
5322     } else if (!strcasecmp(s, "nx-match")) {
5323         *flags = OFPC_FRAG_NX_MATCH;
5324     } else {
5325         return false;
5326     }
5327     return true;
5328 }
5329
5330 /* Converts the OpenFlow 1.1+ port number 'ofp11_port' into an OpenFlow 1.0
5331  * port number and stores the latter in '*ofp10_port', for the purpose of
5332  * decoding OpenFlow 1.1+ protocol messages.  Returns 0 if successful,
5333  * otherwise an OFPERR_* number.  On error, stores OFPP_NONE in '*ofp10_port'.
5334  *
5335  * See the definition of OFP11_MAX for an explanation of the mapping. */
5336 enum ofperr
5337 ofputil_port_from_ofp11(ovs_be32 ofp11_port, ofp_port_t *ofp10_port)
5338 {
5339     uint32_t ofp11_port_h = ntohl(ofp11_port);
5340
5341     if (ofp11_port_h < ofp_to_u16(OFPP_MAX)) {
5342         *ofp10_port = u16_to_ofp(ofp11_port_h);
5343         return 0;
5344     } else if (ofp11_port_h >= ofp11_to_u32(OFPP11_MAX)) {
5345         *ofp10_port = u16_to_ofp(ofp11_port_h - OFPP11_OFFSET);
5346         return 0;
5347     } else {
5348         *ofp10_port = OFPP_NONE;
5349         VLOG_WARN_RL(&bad_ofmsg_rl, "port %"PRIu32" is outside the supported "
5350                      "range 0 through %d or 0x%"PRIx32" through 0x%"PRIx32,
5351                      ofp11_port_h, ofp_to_u16(OFPP_MAX) - 1,
5352                      ofp11_to_u32(OFPP11_MAX), UINT32_MAX);
5353         return OFPERR_OFPBAC_BAD_OUT_PORT;
5354     }
5355 }
5356
5357 /* Returns the OpenFlow 1.1+ port number equivalent to the OpenFlow 1.0 port
5358  * number 'ofp10_port', for encoding OpenFlow 1.1+ protocol messages.
5359  *
5360  * See the definition of OFP11_MAX for an explanation of the mapping. */
5361 ovs_be32
5362 ofputil_port_to_ofp11(ofp_port_t ofp10_port)
5363 {
5364     return htonl(ofp_to_u16(ofp10_port) < ofp_to_u16(OFPP_MAX)
5365                  ? ofp_to_u16(ofp10_port)
5366                  : ofp_to_u16(ofp10_port) + OFPP11_OFFSET);
5367 }
5368
5369 #define OFPUTIL_NAMED_PORTS                     \
5370         OFPUTIL_NAMED_PORT(IN_PORT)             \
5371         OFPUTIL_NAMED_PORT(TABLE)               \
5372         OFPUTIL_NAMED_PORT(NORMAL)              \
5373         OFPUTIL_NAMED_PORT(FLOOD)               \
5374         OFPUTIL_NAMED_PORT(ALL)                 \
5375         OFPUTIL_NAMED_PORT(CONTROLLER)          \
5376         OFPUTIL_NAMED_PORT(LOCAL)               \
5377         OFPUTIL_NAMED_PORT(ANY)
5378
5379 /* For backwards compatibility, so that "none" is recognized as OFPP_ANY */
5380 #define OFPUTIL_NAMED_PORTS_WITH_NONE           \
5381         OFPUTIL_NAMED_PORTS                     \
5382         OFPUTIL_NAMED_PORT(NONE)
5383
5384 /* Stores the port number represented by 's' into '*portp'.  's' may be an
5385  * integer or, for reserved ports, the standard OpenFlow name for the port
5386  * (e.g. "LOCAL").
5387  *
5388  * Returns true if successful, false if 's' is not a valid OpenFlow port number
5389  * or name.  The caller should issue an error message in this case, because
5390  * this function usually does not.  (This gives the caller an opportunity to
5391  * look up the port name another way, e.g. by contacting the switch and listing
5392  * the names of all its ports).
5393  *
5394  * This function accepts OpenFlow 1.0 port numbers.  It also accepts a subset
5395  * of OpenFlow 1.1+ port numbers, mapping those port numbers into the 16-bit
5396  * range as described in include/openflow/openflow-1.1.h. */
5397 bool
5398 ofputil_port_from_string(const char *s, ofp_port_t *portp)
5399 {
5400     uint32_t port32;
5401
5402     *portp = 0;
5403     if (str_to_uint(s, 10, &port32)) {
5404         if (port32 < ofp_to_u16(OFPP_MAX)) {
5405             /* Pass. */
5406         } else if (port32 < ofp_to_u16(OFPP_FIRST_RESV)) {
5407             VLOG_WARN("port %u is a reserved OF1.0 port number that will "
5408                       "be translated to %u when talking to an OF1.1 or "
5409                       "later controller", port32, port32 + OFPP11_OFFSET);
5410         } else if (port32 <= ofp_to_u16(OFPP_LAST_RESV)) {
5411             char name[OFP_MAX_PORT_NAME_LEN];
5412
5413             ofputil_port_to_string(u16_to_ofp(port32), name, sizeof name);
5414             VLOG_WARN_ONCE("referring to port %s as %"PRIu32" is deprecated "
5415                            "for compatibility with OpenFlow 1.1 and later",
5416                            name, port32);
5417         } else if (port32 < ofp11_to_u32(OFPP11_MAX)) {
5418             VLOG_WARN("port %u is outside the supported range 0 through "
5419                       "%"PRIx16" or 0x%x through 0x%"PRIx32, port32,
5420                       UINT16_MAX, ofp11_to_u32(OFPP11_MAX), UINT32_MAX);
5421             return false;
5422         } else {
5423             port32 -= OFPP11_OFFSET;
5424         }
5425
5426         *portp = u16_to_ofp(port32);
5427         return true;
5428     } else {
5429         struct pair {
5430             const char *name;
5431             ofp_port_t value;
5432         };
5433         static const struct pair pairs[] = {
5434 #define OFPUTIL_NAMED_PORT(NAME) {#NAME, OFPP_##NAME},
5435             OFPUTIL_NAMED_PORTS_WITH_NONE
5436 #undef OFPUTIL_NAMED_PORT
5437         };
5438         const struct pair *p;
5439
5440         for (p = pairs; p < &pairs[ARRAY_SIZE(pairs)]; p++) {
5441             if (!strcasecmp(s, p->name)) {
5442                 *portp = p->value;
5443                 return true;
5444             }
5445         }
5446         return false;
5447     }
5448 }
5449
5450 /* Appends to 's' a string representation of the OpenFlow port number 'port'.
5451  * Most ports' string representation is just the port number, but for special
5452  * ports, e.g. OFPP_LOCAL, it is the name, e.g. "LOCAL". */
5453 void
5454 ofputil_format_port(ofp_port_t port, struct ds *s)
5455 {
5456     char name[OFP_MAX_PORT_NAME_LEN];
5457
5458     ofputil_port_to_string(port, name, sizeof name);
5459     ds_put_cstr(s, name);
5460 }
5461
5462 /* Puts in the 'bufsize' byte in 'namebuf' a null-terminated string
5463  * representation of OpenFlow port number 'port'.  Most ports are represented
5464  * as just the port number, but special ports, e.g. OFPP_LOCAL, are represented
5465  * by name, e.g. "LOCAL". */
5466 void
5467 ofputil_port_to_string(ofp_port_t port,
5468                        char namebuf[OFP_MAX_PORT_NAME_LEN], size_t bufsize)
5469 {
5470     switch (port) {
5471 #define OFPUTIL_NAMED_PORT(NAME)                        \
5472         case OFPP_##NAME:                               \
5473             ovs_strlcpy(namebuf, #NAME, bufsize);       \
5474             break;
5475         OFPUTIL_NAMED_PORTS
5476 #undef OFPUTIL_NAMED_PORT
5477
5478     default:
5479         snprintf(namebuf, bufsize, "%"PRIu16, port);
5480         break;
5481     }
5482 }
5483
5484 /* Stores the group id represented by 's' into '*group_idp'.  's' may be an
5485  * integer or, for reserved group IDs, the standard OpenFlow name for the group
5486  * (either "ANY" or "ALL").
5487  *
5488  * Returns true if successful, false if 's' is not a valid OpenFlow group ID or
5489  * name. */
5490 bool
5491 ofputil_group_from_string(const char *s, uint32_t *group_idp)
5492 {
5493     if (!strcasecmp(s, "any")) {
5494         *group_idp = OFPG11_ANY;
5495     } else if (!strcasecmp(s, "all")) {
5496         *group_idp = OFPG11_ALL;
5497     } else if (!str_to_uint(s, 10, group_idp)) {
5498         VLOG_WARN("%s is not a valid group ID.  (Valid group IDs are "
5499                   "32-bit nonnegative integers or the keywords ANY or "
5500                   "ALL.)", s);
5501         return false;
5502     }
5503
5504     return true;
5505 }
5506
5507 /* Appends to 's' a string representation of the OpenFlow group ID 'group_id'.
5508  * Most groups' string representation is just the number, but for special
5509  * groups, e.g. OFPG11_ALL, it is the name, e.g. "ALL". */
5510 void
5511 ofputil_format_group(uint32_t group_id, struct ds *s)
5512 {
5513     char name[MAX_GROUP_NAME_LEN];
5514
5515     ofputil_group_to_string(group_id, name, sizeof name);
5516     ds_put_cstr(s, name);
5517 }
5518
5519
5520 /* Puts in the 'bufsize' byte in 'namebuf' a null-terminated string
5521  * representation of OpenFlow group ID 'group_id'.  Most group are represented
5522  * as just their number, but special groups, e.g. OFPG11_ALL, are represented
5523  * by name, e.g. "ALL". */
5524 void
5525 ofputil_group_to_string(uint32_t group_id,
5526                         char namebuf[MAX_GROUP_NAME_LEN + 1], size_t bufsize)
5527 {
5528     switch (group_id) {
5529     case OFPG11_ALL:
5530         ovs_strlcpy(namebuf, "ALL", bufsize);
5531         break;
5532
5533     case OFPG11_ANY:
5534         ovs_strlcpy(namebuf, "ANY", bufsize);
5535         break;
5536
5537     default:
5538         snprintf(namebuf, bufsize, "%"PRIu32, group_id);
5539         break;
5540     }
5541 }
5542
5543 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
5544  * 'ofp_version', tries to pull the first element from the array.  If
5545  * successful, initializes '*pp' with an abstract representation of the
5546  * port and returns 0.  If no ports remain to be decoded, returns EOF.
5547  * On an error, returns a positive OFPERR_* value. */
5548 int
5549 ofputil_pull_phy_port(enum ofp_version ofp_version, struct ofpbuf *b,
5550                       struct ofputil_phy_port *pp)
5551 {
5552     switch (ofp_version) {
5553     case OFP10_VERSION: {
5554         const struct ofp10_phy_port *opp = ofpbuf_try_pull(b, sizeof *opp);
5555         return opp ? ofputil_decode_ofp10_phy_port(pp, opp) : EOF;
5556     }
5557     case OFP11_VERSION:
5558     case OFP12_VERSION:
5559     case OFP13_VERSION: {
5560         const struct ofp11_port *op = ofpbuf_try_pull(b, sizeof *op);
5561         return op ? ofputil_decode_ofp11_port(pp, op) : EOF;
5562     }
5563     case OFP14_VERSION:
5564         OVS_NOT_REACHED();
5565         break;
5566     default:
5567         OVS_NOT_REACHED();
5568     }
5569 }
5570
5571 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
5572  * 'ofp_version', returns the number of elements. */
5573 size_t ofputil_count_phy_ports(uint8_t ofp_version, struct ofpbuf *b)
5574 {
5575     return ofpbuf_size(b) / ofputil_get_phy_port_size(ofp_version);
5576 }
5577
5578 /* ofp-util.def lists the mapping from names to action. */
5579 static const char *const names[OFPUTIL_N_ACTIONS] = {
5580     NULL,
5581 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)             NAME,
5582 #define OFPAT11_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) NAME,
5583 #define OFPAT13_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) NAME,
5584 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)   NAME,
5585 #include "ofp-util.def"
5586 };
5587
5588 /* Returns the 'enum ofputil_action_code' corresponding to 'name' (e.g. if
5589  * 'name' is "output" then the return value is OFPUTIL_OFPAT10_OUTPUT), or -1
5590  * if 'name' is not the name of any action. */
5591 int
5592 ofputil_action_code_from_name(const char *name)
5593 {
5594     const char *const *p;
5595
5596     for (p = names; p < &names[ARRAY_SIZE(names)]; p++) {
5597         if (*p && !strcasecmp(name, *p)) {
5598             return p - names;
5599         }
5600     }
5601     return -1;
5602 }
5603
5604 /* Returns name corresponding to the 'enum ofputil_action_code',
5605  * or "Unkonwn action", if the name is not available. */
5606 const char *
5607 ofputil_action_name_from_code(enum ofputil_action_code code)
5608 {
5609     return code < (int)OFPUTIL_N_ACTIONS && names[code] ? names[code]
5610         : "Unknown action";
5611 }
5612
5613 enum ofputil_action_code
5614 ofputil_action_code_from_ofp13_action(enum ofp13_action_type type)
5615 {
5616     switch (type) {
5617
5618 #define OFPAT13_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)  \
5619     case ENUM:                                          \
5620         return OFPUTIL_##ENUM;
5621 #include "ofp-util.def"
5622
5623     default:
5624         return OFPUTIL_ACTION_INVALID;
5625     }
5626 }
5627
5628 /* Appends an action of the type specified by 'code' to 'buf' and returns the
5629  * action.  Initializes the parts of 'action' that identify it as having type
5630  * <ENUM> and length 'sizeof *action' and zeros the rest.  For actions that
5631  * have variable length, the length used and cleared is that of struct
5632  * <STRUCT>.  */
5633 void *
5634 ofputil_put_action(enum ofputil_action_code code, struct ofpbuf *buf)
5635 {
5636     switch (code) {
5637     case OFPUTIL_ACTION_INVALID:
5638 #define OFPAT13_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) case OFPUTIL_##ENUM:
5639 #include "ofp-util.def"
5640         OVS_NOT_REACHED();
5641
5642 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                  \
5643     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
5644 #define OFPAT11_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)      \
5645     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
5646 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)        \
5647     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
5648 #include "ofp-util.def"
5649     }
5650     OVS_NOT_REACHED();
5651 }
5652
5653 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                        \
5654     void                                                        \
5655     ofputil_init_##ENUM(struct STRUCT *s)                       \
5656     {                                                           \
5657         memset(s, 0, sizeof *s);                                \
5658         s->type = htons(ENUM);                                  \
5659         s->len = htons(sizeof *s);                              \
5660     }                                                           \
5661                                                                 \
5662     struct STRUCT *                                             \
5663     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
5664     {                                                           \
5665         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
5666         ofputil_init_##ENUM(s);                                 \
5667         return s;                                               \
5668     }
5669 #define OFPAT11_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) \
5670     OFPAT10_ACTION(ENUM, STRUCT, NAME)
5671 #define OFPAT13_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) \
5672     OFPAT10_ACTION(ENUM, STRUCT, NAME)
5673 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)            \
5674     void                                                        \
5675     ofputil_init_##ENUM(struct STRUCT *s)                       \
5676     {                                                           \
5677         memset(s, 0, sizeof *s);                                \
5678         s->type = htons(OFPAT10_VENDOR);                        \
5679         s->len = htons(sizeof *s);                              \
5680         s->vendor = htonl(NX_VENDOR_ID);                        \
5681         s->subtype = htons(ENUM);                               \
5682     }                                                           \
5683                                                                 \
5684     struct STRUCT *                                             \
5685     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
5686     {                                                           \
5687         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
5688         ofputil_init_##ENUM(s);                                 \
5689         return s;                                               \
5690     }
5691 #include "ofp-util.def"
5692
5693 static void
5694 ofputil_normalize_match__(struct match *match, bool may_log)
5695 {
5696     enum {
5697         MAY_NW_ADDR     = 1 << 0, /* nw_src, nw_dst */
5698         MAY_TP_ADDR     = 1 << 1, /* tp_src, tp_dst */
5699         MAY_NW_PROTO    = 1 << 2, /* nw_proto */
5700         MAY_IPVx        = 1 << 3, /* tos, frag, ttl */
5701         MAY_ARP_SHA     = 1 << 4, /* arp_sha */
5702         MAY_ARP_THA     = 1 << 5, /* arp_tha */
5703         MAY_IPV6        = 1 << 6, /* ipv6_src, ipv6_dst, ipv6_label */
5704         MAY_ND_TARGET   = 1 << 7, /* nd_target */
5705         MAY_MPLS        = 1 << 8, /* mpls label and tc */
5706     } may_match;
5707
5708     struct flow_wildcards wc;
5709
5710     /* Figure out what fields may be matched. */
5711     if (match->flow.dl_type == htons(ETH_TYPE_IP)) {
5712         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_NW_ADDR;
5713         if (match->flow.nw_proto == IPPROTO_TCP ||
5714             match->flow.nw_proto == IPPROTO_UDP ||
5715             match->flow.nw_proto == IPPROTO_SCTP ||
5716             match->flow.nw_proto == IPPROTO_ICMP) {
5717             may_match |= MAY_TP_ADDR;
5718         }
5719     } else if (match->flow.dl_type == htons(ETH_TYPE_IPV6)) {
5720         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_IPV6;
5721         if (match->flow.nw_proto == IPPROTO_TCP ||
5722             match->flow.nw_proto == IPPROTO_UDP ||
5723             match->flow.nw_proto == IPPROTO_SCTP) {
5724             may_match |= MAY_TP_ADDR;
5725         } else if (match->flow.nw_proto == IPPROTO_ICMPV6) {
5726             may_match |= MAY_TP_ADDR;
5727             if (match->flow.tp_src == htons(ND_NEIGHBOR_SOLICIT)) {
5728                 may_match |= MAY_ND_TARGET | MAY_ARP_SHA;
5729             } else if (match->flow.tp_src == htons(ND_NEIGHBOR_ADVERT)) {
5730                 may_match |= MAY_ND_TARGET | MAY_ARP_THA;
5731             }
5732         }
5733     } else if (match->flow.dl_type == htons(ETH_TYPE_ARP) ||
5734                match->flow.dl_type == htons(ETH_TYPE_RARP)) {
5735         may_match = MAY_NW_PROTO | MAY_NW_ADDR | MAY_ARP_SHA | MAY_ARP_THA;
5736     } else if (eth_type_mpls(match->flow.dl_type)) {
5737         may_match = MAY_MPLS;
5738     } else {
5739         may_match = 0;
5740     }
5741
5742     /* Clear the fields that may not be matched. */
5743     wc = match->wc;
5744     if (!(may_match & MAY_NW_ADDR)) {
5745         wc.masks.nw_src = wc.masks.nw_dst = htonl(0);
5746     }
5747     if (!(may_match & MAY_TP_ADDR)) {
5748         wc.masks.tp_src = wc.masks.tp_dst = htons(0);
5749     }
5750     if (!(may_match & MAY_NW_PROTO)) {
5751         wc.masks.nw_proto = 0;
5752     }
5753     if (!(may_match & MAY_IPVx)) {
5754         wc.masks.nw_tos = 0;
5755         wc.masks.nw_ttl = 0;
5756     }
5757     if (!(may_match & MAY_ARP_SHA)) {
5758         memset(wc.masks.arp_sha, 0, ETH_ADDR_LEN);
5759     }
5760     if (!(may_match & MAY_ARP_THA)) {
5761         memset(wc.masks.arp_tha, 0, ETH_ADDR_LEN);
5762     }
5763     if (!(may_match & MAY_IPV6)) {
5764         wc.masks.ipv6_src = wc.masks.ipv6_dst = in6addr_any;
5765         wc.masks.ipv6_label = htonl(0);
5766     }
5767     if (!(may_match & MAY_ND_TARGET)) {
5768         wc.masks.nd_target = in6addr_any;
5769     }
5770     if (!(may_match & MAY_MPLS)) {
5771         memset(wc.masks.mpls_lse, 0, sizeof wc.masks.mpls_lse);
5772     }
5773
5774     /* Log any changes. */
5775     if (!flow_wildcards_equal(&wc, &match->wc)) {
5776         bool log = may_log && !VLOG_DROP_INFO(&bad_ofmsg_rl);
5777         char *pre = log ? match_to_string(match, OFP_DEFAULT_PRIORITY) : NULL;
5778
5779         match->wc = wc;
5780         match_zero_wildcarded_fields(match);
5781
5782         if (log) {
5783             char *post = match_to_string(match, OFP_DEFAULT_PRIORITY);
5784             VLOG_INFO("normalization changed ofp_match, details:");
5785             VLOG_INFO(" pre: %s", pre);
5786             VLOG_INFO("post: %s", post);
5787             free(pre);
5788             free(post);
5789         }
5790     }
5791 }
5792
5793 /* "Normalizes" the wildcards in 'match'.  That means:
5794  *
5795  *    1. If the type of level N is known, then only the valid fields for that
5796  *       level may be specified.  For example, ARP does not have a TOS field,
5797  *       so nw_tos must be wildcarded if 'match' specifies an ARP flow.
5798  *       Similarly, IPv4 does not have any IPv6 addresses, so ipv6_src and
5799  *       ipv6_dst (and other fields) must be wildcarded if 'match' specifies an
5800  *       IPv4 flow.
5801  *
5802  *    2. If the type of level N is not known (or not understood by Open
5803  *       vSwitch), then no fields at all for that level may be specified.  For
5804  *       example, Open vSwitch does not understand SCTP, an L4 protocol, so the
5805  *       L4 fields tp_src and tp_dst must be wildcarded if 'match' specifies an
5806  *       SCTP flow.
5807  *
5808  * If this function changes 'match', it logs a rate-limited informational
5809  * message. */
5810 void
5811 ofputil_normalize_match(struct match *match)
5812 {
5813     ofputil_normalize_match__(match, true);
5814 }
5815
5816 /* Same as ofputil_normalize_match() without the logging.  Thus, this function
5817  * is suitable for a program's internal use, whereas ofputil_normalize_match()
5818  * sense for use on flows received from elsewhere (so that a bug in the program
5819  * that sent them can be reported and corrected). */
5820 void
5821 ofputil_normalize_match_quiet(struct match *match)
5822 {
5823     ofputil_normalize_match__(match, false);
5824 }
5825
5826 /* Parses a key or a key-value pair from '*stringp'.
5827  *
5828  * On success: Stores the key into '*keyp'.  Stores the value, if present, into
5829  * '*valuep', otherwise an empty string.  Advances '*stringp' past the end of
5830  * the key-value pair, preparing it for another call.  '*keyp' and '*valuep'
5831  * are substrings of '*stringp' created by replacing some of its bytes by null
5832  * terminators.  Returns true.
5833  *
5834  * If '*stringp' is just white space or commas, sets '*keyp' and '*valuep' to
5835  * NULL and returns false. */
5836 bool
5837 ofputil_parse_key_value(char **stringp, char **keyp, char **valuep)
5838 {
5839     char *pos, *key, *value;
5840     size_t key_len;
5841
5842     pos = *stringp;
5843     pos += strspn(pos, ", \t\r\n");
5844     if (*pos == '\0') {
5845         *keyp = *valuep = NULL;
5846         return false;
5847     }
5848
5849     key = pos;
5850     key_len = strcspn(pos, ":=(, \t\r\n");
5851     if (key[key_len] == ':' || key[key_len] == '=') {
5852         /* The value can be separated by a colon. */
5853         size_t value_len;
5854
5855         value = key + key_len + 1;
5856         value_len = strcspn(value, ", \t\r\n");
5857         pos = value + value_len + (value[value_len] != '\0');
5858         value[value_len] = '\0';
5859     } else if (key[key_len] == '(') {
5860         /* The value can be surrounded by balanced parentheses.  The outermost
5861          * set of parentheses is removed. */
5862         int level = 1;
5863         size_t value_len;
5864
5865         value = key + key_len + 1;
5866         for (value_len = 0; level > 0; value_len++) {
5867             switch (value[value_len]) {
5868             case '\0':
5869                 level = 0;
5870                 break;
5871
5872             case '(':
5873                 level++;
5874                 break;
5875
5876             case ')':
5877                 level--;
5878                 break;
5879             }
5880         }
5881         value[value_len - 1] = '\0';
5882         pos = value + value_len;
5883     } else {
5884         /* There might be no value at all. */
5885         value = key + key_len;  /* Will become the empty string below. */
5886         pos = key + key_len + (key[key_len] != '\0');
5887     }
5888     key[key_len] = '\0';
5889
5890     *stringp = pos;
5891     *keyp = key;
5892     *valuep = value;
5893     return true;
5894 }
5895
5896 /* Encode a dump ports request for 'port', the encoded message
5897  * will be for Open Flow version 'ofp_version'. Returns message
5898  * as a struct ofpbuf. Returns encoded message on success, NULL on error */
5899 struct ofpbuf *
5900 ofputil_encode_dump_ports_request(enum ofp_version ofp_version, ofp_port_t port)
5901 {
5902     struct ofpbuf *request;
5903
5904     switch (ofp_version) {
5905     case OFP10_VERSION: {
5906         struct ofp10_port_stats_request *req;
5907         request = ofpraw_alloc(OFPRAW_OFPST10_PORT_REQUEST, ofp_version, 0);
5908         req = ofpbuf_put_zeros(request, sizeof *req);
5909         req->port_no = htons(ofp_to_u16(port));
5910         break;
5911     }
5912     case OFP11_VERSION:
5913     case OFP12_VERSION:
5914     case OFP13_VERSION:
5915     case OFP14_VERSION:{
5916         struct ofp11_port_stats_request *req;
5917         request = ofpraw_alloc(OFPRAW_OFPST11_PORT_REQUEST, ofp_version, 0);
5918         req = ofpbuf_put_zeros(request, sizeof *req);
5919         req->port_no = ofputil_port_to_ofp11(port);
5920         break;
5921     }
5922     default:
5923         OVS_NOT_REACHED();
5924     }
5925
5926     return request;
5927 }
5928
5929 static void
5930 ofputil_port_stats_to_ofp10(const struct ofputil_port_stats *ops,
5931                             struct ofp10_port_stats *ps10)
5932 {
5933     ps10->port_no = htons(ofp_to_u16(ops->port_no));
5934     memset(ps10->pad, 0, sizeof ps10->pad);
5935     put_32aligned_be64(&ps10->rx_packets, htonll(ops->stats.rx_packets));
5936     put_32aligned_be64(&ps10->tx_packets, htonll(ops->stats.tx_packets));
5937     put_32aligned_be64(&ps10->rx_bytes, htonll(ops->stats.rx_bytes));
5938     put_32aligned_be64(&ps10->tx_bytes, htonll(ops->stats.tx_bytes));
5939     put_32aligned_be64(&ps10->rx_dropped, htonll(ops->stats.rx_dropped));
5940     put_32aligned_be64(&ps10->tx_dropped, htonll(ops->stats.tx_dropped));
5941     put_32aligned_be64(&ps10->rx_errors, htonll(ops->stats.rx_errors));
5942     put_32aligned_be64(&ps10->tx_errors, htonll(ops->stats.tx_errors));
5943     put_32aligned_be64(&ps10->rx_frame_err, htonll(ops->stats.rx_frame_errors));
5944     put_32aligned_be64(&ps10->rx_over_err, htonll(ops->stats.rx_over_errors));
5945     put_32aligned_be64(&ps10->rx_crc_err, htonll(ops->stats.rx_crc_errors));
5946     put_32aligned_be64(&ps10->collisions, htonll(ops->stats.collisions));
5947 }
5948
5949 static void
5950 ofputil_port_stats_to_ofp11(const struct ofputil_port_stats *ops,
5951                             struct ofp11_port_stats *ps11)
5952 {
5953     ps11->port_no = ofputil_port_to_ofp11(ops->port_no);
5954     memset(ps11->pad, 0, sizeof ps11->pad);
5955     ps11->rx_packets = htonll(ops->stats.rx_packets);
5956     ps11->tx_packets = htonll(ops->stats.tx_packets);
5957     ps11->rx_bytes = htonll(ops->stats.rx_bytes);
5958     ps11->tx_bytes = htonll(ops->stats.tx_bytes);
5959     ps11->rx_dropped = htonll(ops->stats.rx_dropped);
5960     ps11->tx_dropped = htonll(ops->stats.tx_dropped);
5961     ps11->rx_errors = htonll(ops->stats.rx_errors);
5962     ps11->tx_errors = htonll(ops->stats.tx_errors);
5963     ps11->rx_frame_err = htonll(ops->stats.rx_frame_errors);
5964     ps11->rx_over_err = htonll(ops->stats.rx_over_errors);
5965     ps11->rx_crc_err = htonll(ops->stats.rx_crc_errors);
5966     ps11->collisions = htonll(ops->stats.collisions);
5967 }
5968
5969 static void
5970 ofputil_port_stats_to_ofp13(const struct ofputil_port_stats *ops,
5971                             struct ofp13_port_stats *ps13)
5972 {
5973     ofputil_port_stats_to_ofp11(ops, &ps13->ps);
5974     ps13->duration_sec = htonl(ops->duration_sec);
5975     ps13->duration_nsec = htonl(ops->duration_nsec);
5976 }
5977
5978
5979 /* Encode a ports stat for 'ops' and append it to 'replies'. */
5980 void
5981 ofputil_append_port_stat(struct list *replies,
5982                          const struct ofputil_port_stats *ops)
5983 {
5984     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
5985     struct ofp_header *oh = ofpbuf_data(msg);
5986
5987     switch ((enum ofp_version)oh->version) {
5988     case OFP13_VERSION: {
5989         struct ofp13_port_stats *reply = ofpmp_append(replies, sizeof *reply);
5990         ofputil_port_stats_to_ofp13(ops, reply);
5991         break;
5992     }
5993     case OFP12_VERSION:
5994     case OFP11_VERSION: {
5995         struct ofp11_port_stats *reply = ofpmp_append(replies, sizeof *reply);
5996         ofputil_port_stats_to_ofp11(ops, reply);
5997         break;
5998     }
5999
6000     case OFP10_VERSION: {
6001         struct ofp10_port_stats *reply = ofpmp_append(replies, sizeof *reply);
6002         ofputil_port_stats_to_ofp10(ops, reply);
6003         break;
6004     }
6005
6006     case OFP14_VERSION:
6007         OVS_NOT_REACHED();
6008         break;
6009
6010     default:
6011         OVS_NOT_REACHED();
6012     }
6013 }
6014
6015 static enum ofperr
6016 ofputil_port_stats_from_ofp10(struct ofputil_port_stats *ops,
6017                               const struct ofp10_port_stats *ps10)
6018 {
6019     memset(ops, 0, sizeof *ops);
6020
6021     ops->port_no = u16_to_ofp(ntohs(ps10->port_no));
6022     ops->stats.rx_packets = ntohll(get_32aligned_be64(&ps10->rx_packets));
6023     ops->stats.tx_packets = ntohll(get_32aligned_be64(&ps10->tx_packets));
6024     ops->stats.rx_bytes = ntohll(get_32aligned_be64(&ps10->rx_bytes));
6025     ops->stats.tx_bytes = ntohll(get_32aligned_be64(&ps10->tx_bytes));
6026     ops->stats.rx_dropped = ntohll(get_32aligned_be64(&ps10->rx_dropped));
6027     ops->stats.tx_dropped = ntohll(get_32aligned_be64(&ps10->tx_dropped));
6028     ops->stats.rx_errors = ntohll(get_32aligned_be64(&ps10->rx_errors));
6029     ops->stats.tx_errors = ntohll(get_32aligned_be64(&ps10->tx_errors));
6030     ops->stats.rx_frame_errors =
6031         ntohll(get_32aligned_be64(&ps10->rx_frame_err));
6032     ops->stats.rx_over_errors = ntohll(get_32aligned_be64(&ps10->rx_over_err));
6033     ops->stats.rx_crc_errors = ntohll(get_32aligned_be64(&ps10->rx_crc_err));
6034     ops->stats.collisions = ntohll(get_32aligned_be64(&ps10->collisions));
6035     ops->duration_sec = ops->duration_nsec = UINT32_MAX;
6036
6037     return 0;
6038 }
6039
6040 static enum ofperr
6041 ofputil_port_stats_from_ofp11(struct ofputil_port_stats *ops,
6042                               const struct ofp11_port_stats *ps11)
6043 {
6044     enum ofperr error;
6045
6046     memset(ops, 0, sizeof *ops);
6047     error = ofputil_port_from_ofp11(ps11->port_no, &ops->port_no);
6048     if (error) {
6049         return error;
6050     }
6051
6052     ops->stats.rx_packets = ntohll(ps11->rx_packets);
6053     ops->stats.tx_packets = ntohll(ps11->tx_packets);
6054     ops->stats.rx_bytes = ntohll(ps11->rx_bytes);
6055     ops->stats.tx_bytes = ntohll(ps11->tx_bytes);
6056     ops->stats.rx_dropped = ntohll(ps11->rx_dropped);
6057     ops->stats.tx_dropped = ntohll(ps11->tx_dropped);
6058     ops->stats.rx_errors = ntohll(ps11->rx_errors);
6059     ops->stats.tx_errors = ntohll(ps11->tx_errors);
6060     ops->stats.rx_frame_errors = ntohll(ps11->rx_frame_err);
6061     ops->stats.rx_over_errors = ntohll(ps11->rx_over_err);
6062     ops->stats.rx_crc_errors = ntohll(ps11->rx_crc_err);
6063     ops->stats.collisions = ntohll(ps11->collisions);
6064     ops->duration_sec = ops->duration_nsec = UINT32_MAX;
6065
6066     return 0;
6067 }
6068
6069 static enum ofperr
6070 ofputil_port_stats_from_ofp13(struct ofputil_port_stats *ops,
6071                               const struct ofp13_port_stats *ps13)
6072 {
6073     enum ofperr error = ofputil_port_stats_from_ofp11(ops, &ps13->ps);
6074     if (!error) {
6075         ops->duration_sec = ntohl(ps13->duration_sec);
6076         ops->duration_nsec = ntohl(ps13->duration_nsec);
6077     }
6078     return error;
6079 }
6080
6081 static size_t
6082 ofputil_get_port_stats_size(enum ofp_version ofp_version)
6083 {
6084     switch (ofp_version) {
6085     case OFP10_VERSION:
6086         return sizeof(struct ofp10_port_stats);
6087     case OFP11_VERSION:
6088     case OFP12_VERSION:
6089         return sizeof(struct ofp11_port_stats);
6090     case OFP13_VERSION:
6091         return sizeof(struct ofp13_port_stats);
6092     case OFP14_VERSION:
6093         OVS_NOT_REACHED();
6094         return 0;
6095     default:
6096         OVS_NOT_REACHED();
6097     }
6098 }
6099
6100 /* Returns the number of port stats elements in OFPTYPE_PORT_STATS_REPLY
6101  * message 'oh'. */
6102 size_t
6103 ofputil_count_port_stats(const struct ofp_header *oh)
6104 {
6105     struct ofpbuf b;
6106
6107     ofpbuf_use_const(&b, oh, ntohs(oh->length));
6108     ofpraw_pull_assert(&b);
6109
6110     return ofpbuf_size(&b) / ofputil_get_port_stats_size(oh->version);
6111 }
6112
6113 /* Converts an OFPST_PORT_STATS reply in 'msg' into an abstract
6114  * ofputil_port_stats in 'ps'.
6115  *
6116  * Multiple OFPST_PORT_STATS replies can be packed into a single OpenFlow
6117  * message.  Calling this function multiple times for a single 'msg' iterates
6118  * through the replies.  The caller must initially leave 'msg''s layer pointers
6119  * null and not modify them between calls.
6120  *
6121  * Returns 0 if successful, EOF if no replies were left in this 'msg',
6122  * otherwise a positive errno value. */
6123 int
6124 ofputil_decode_port_stats(struct ofputil_port_stats *ps, struct ofpbuf *msg)
6125 {
6126     enum ofperr error;
6127     enum ofpraw raw;
6128
6129     error = (msg->l2
6130              ? ofpraw_decode(&raw, msg->l2)
6131              : ofpraw_pull(&raw, msg));
6132     if (error) {
6133         return error;
6134     }
6135
6136     if (!ofpbuf_size(msg)) {
6137         return EOF;
6138     } else if (raw == OFPRAW_OFPST13_PORT_REPLY) {
6139         const struct ofp13_port_stats *ps13;
6140
6141         ps13 = ofpbuf_try_pull(msg, sizeof *ps13);
6142         if (!ps13) {
6143             goto bad_len;
6144         }
6145         return ofputil_port_stats_from_ofp13(ps, ps13);
6146     } else if (raw == OFPRAW_OFPST11_PORT_REPLY) {
6147         const struct ofp11_port_stats *ps11;
6148
6149         ps11 = ofpbuf_try_pull(msg, sizeof *ps11);
6150         if (!ps11) {
6151             goto bad_len;
6152         }
6153         return ofputil_port_stats_from_ofp11(ps, ps11);
6154     } else if (raw == OFPRAW_OFPST10_PORT_REPLY) {
6155         const struct ofp10_port_stats *ps10;
6156
6157         ps10 = ofpbuf_try_pull(msg, sizeof *ps10);
6158         if (!ps10) {
6159             goto bad_len;
6160         }
6161         return ofputil_port_stats_from_ofp10(ps, ps10);
6162     } else {
6163         OVS_NOT_REACHED();
6164     }
6165
6166  bad_len:
6167     VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_PORT reply has %"PRIu32" leftover "
6168                  "bytes at end", ofpbuf_size(msg));
6169     return OFPERR_OFPBRC_BAD_LEN;
6170 }
6171
6172 /* Parse a port status request message into a 16 bit OpenFlow 1.0
6173  * port number and stores the latter in '*ofp10_port'.
6174  * Returns 0 if successful, otherwise an OFPERR_* number. */
6175 enum ofperr
6176 ofputil_decode_port_stats_request(const struct ofp_header *request,
6177                                   ofp_port_t *ofp10_port)
6178 {
6179     switch ((enum ofp_version)request->version) {
6180     case OFP13_VERSION:
6181     case OFP12_VERSION:
6182     case OFP11_VERSION: {
6183         const struct ofp11_port_stats_request *psr11 = ofpmsg_body(request);
6184         return ofputil_port_from_ofp11(psr11->port_no, ofp10_port);
6185     }
6186
6187     case OFP10_VERSION: {
6188         const struct ofp10_port_stats_request *psr10 = ofpmsg_body(request);
6189         *ofp10_port = u16_to_ofp(ntohs(psr10->port_no));
6190         return 0;
6191     }
6192
6193     case OFP14_VERSION:
6194         OVS_NOT_REACHED();
6195         break;
6196
6197     default:
6198         OVS_NOT_REACHED();
6199     }
6200 }
6201
6202 /* Frees all of the "struct ofputil_bucket"s in the 'buckets' list. */
6203 void
6204 ofputil_bucket_list_destroy(struct list *buckets)
6205 {
6206     struct ofputil_bucket *bucket, *next_bucket;
6207
6208     LIST_FOR_EACH_SAFE (bucket, next_bucket, list_node, buckets) {
6209         list_remove(&bucket->list_node);
6210         free(bucket->ofpacts);
6211         free(bucket);
6212     }
6213 }
6214
6215 /* Returns an OpenFlow group stats request for OpenFlow version 'ofp_version',
6216  * that requests stats for group 'group_id'.  (Use OFPG_ALL to request stats
6217  * for all groups.)
6218  *
6219  * Group statistics include packet and byte counts for each group. */
6220 struct ofpbuf *
6221 ofputil_encode_group_stats_request(enum ofp_version ofp_version,
6222                                    uint32_t group_id)
6223 {
6224     struct ofpbuf *request;
6225
6226     switch (ofp_version) {
6227     case OFP10_VERSION:
6228         ovs_fatal(0, "dump-group-stats needs OpenFlow 1.1 or later "
6229                      "(\'-O OpenFlow11\')");
6230     case OFP11_VERSION:
6231     case OFP12_VERSION:
6232     case OFP13_VERSION:
6233     case OFP14_VERSION: {
6234         struct ofp11_group_stats_request *req;
6235         request = ofpraw_alloc(OFPRAW_OFPST11_GROUP_REQUEST, ofp_version, 0);
6236         req = ofpbuf_put_zeros(request, sizeof *req);
6237         req->group_id = htonl(group_id);
6238         break;
6239     }
6240     default:
6241         OVS_NOT_REACHED();
6242     }
6243
6244     return request;
6245 }
6246
6247 /* Returns an OpenFlow group description request for OpenFlow version
6248  * 'ofp_version', that requests stats for group 'group_id'.  (Use OFPG_ALL to
6249  * request stats for all groups.)
6250  *
6251  * Group descriptions include the bucket and action configuration for each
6252  * group. */
6253 struct ofpbuf *
6254 ofputil_encode_group_desc_request(enum ofp_version ofp_version)
6255 {
6256     struct ofpbuf *request;
6257
6258     switch (ofp_version) {
6259     case OFP10_VERSION:
6260         ovs_fatal(0, "dump-groups needs OpenFlow 1.1 or later "
6261                      "(\'-O OpenFlow11\')");
6262     case OFP11_VERSION:
6263     case OFP12_VERSION:
6264     case OFP13_VERSION:
6265     case OFP14_VERSION:
6266         request = ofpraw_alloc(OFPRAW_OFPST11_GROUP_DESC_REQUEST, ofp_version, 0);
6267         break;
6268     default:
6269         OVS_NOT_REACHED();
6270     }
6271
6272     return request;
6273 }
6274
6275 static void *
6276 ofputil_group_stats_to_ofp11(const struct ofputil_group_stats *ogs,
6277                              size_t base_len, struct list *replies)
6278 {
6279     struct ofp11_bucket_counter *bc11;
6280     struct ofp11_group_stats *gs11;
6281     size_t length;
6282     int i;
6283
6284     length = base_len + sizeof(struct ofp11_bucket_counter) * ogs->n_buckets;
6285
6286     gs11 = ofpmp_append(replies, length);
6287     memset(gs11, 0, base_len);
6288     gs11->length = htons(length);
6289     gs11->group_id = htonl(ogs->group_id);
6290     gs11->ref_count = htonl(ogs->ref_count);
6291     gs11->packet_count = htonll(ogs->packet_count);
6292     gs11->byte_count = htonll(ogs->byte_count);
6293
6294     bc11 = (void *) (((uint8_t *) gs11) + base_len);
6295     for (i = 0; i < ogs->n_buckets; i++) {
6296         const struct bucket_counter *obc = &ogs->bucket_stats[i];
6297
6298         bc11[i].packet_count = htonll(obc->packet_count);
6299         bc11[i].byte_count = htonll(obc->byte_count);
6300     }
6301
6302     return gs11;
6303 }
6304
6305 static void
6306 ofputil_append_of13_group_stats(const struct ofputil_group_stats *ogs,
6307                                 struct list *replies)
6308 {
6309     struct ofp13_group_stats *gs13;
6310
6311     gs13 = ofputil_group_stats_to_ofp11(ogs, sizeof *gs13, replies);
6312     gs13->duration_sec = htonl(ogs->duration_sec);
6313     gs13->duration_nsec = htonl(ogs->duration_nsec);
6314 }
6315
6316 /* Encodes 'ogs' properly for the format of the list of group statistics
6317  * replies already begun in 'replies' and appends it to the list.  'replies'
6318  * must have originally been initialized with ofpmp_init(). */
6319 void
6320 ofputil_append_group_stats(struct list *replies,
6321                            const struct ofputil_group_stats *ogs)
6322 {
6323     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
6324     struct ofp_header *oh = ofpbuf_data(msg);
6325
6326     switch ((enum ofp_version)oh->version) {
6327     case OFP11_VERSION:
6328     case OFP12_VERSION:
6329         ofputil_group_stats_to_ofp11(ogs, sizeof(struct ofp11_group_stats),
6330                                      replies);
6331         break;
6332
6333     case OFP13_VERSION:
6334         ofputil_append_of13_group_stats(ogs, replies);
6335         break;
6336
6337     case OFP14_VERSION:
6338         OVS_NOT_REACHED();
6339         break;
6340
6341     case OFP10_VERSION:
6342     default:
6343         OVS_NOT_REACHED();
6344     }
6345 }
6346
6347 /* Returns an OpenFlow group features request for OpenFlow version
6348  * 'ofp_version'. */
6349 struct ofpbuf *
6350 ofputil_encode_group_features_request(enum ofp_version ofp_version)
6351 {
6352     struct ofpbuf *request = NULL;
6353
6354     switch (ofp_version) {
6355     case OFP10_VERSION:
6356     case OFP11_VERSION:
6357         ovs_fatal(0, "dump-group-features needs OpenFlow 1.2 or later "
6358                      "(\'-O OpenFlow12\')");
6359     case OFP12_VERSION:
6360     case OFP13_VERSION:
6361     case OFP14_VERSION:
6362         request = ofpraw_alloc(OFPRAW_OFPST12_GROUP_FEATURES_REQUEST,
6363                                ofp_version, 0);
6364         break;
6365     default:
6366         OVS_NOT_REACHED();
6367     }
6368
6369     return request;
6370 }
6371
6372 /* Returns a OpenFlow message that encodes 'features' properly as a reply to
6373  * group features request 'request'. */
6374 struct ofpbuf *
6375 ofputil_encode_group_features_reply(
6376     const struct ofputil_group_features *features,
6377     const struct ofp_header *request)
6378 {
6379     struct ofp12_group_features_stats *ogf;
6380     struct ofpbuf *reply;
6381
6382     reply = ofpraw_alloc_xid(OFPRAW_OFPST12_GROUP_FEATURES_REPLY,
6383                              request->version, request->xid, 0);
6384     ogf = ofpbuf_put_zeros(reply, sizeof *ogf);
6385     ogf->types = htonl(features->types);
6386     ogf->capabilities = htonl(features->capabilities);
6387     ogf->max_groups[0] = htonl(features->max_groups[0]);
6388     ogf->max_groups[1] = htonl(features->max_groups[1]);
6389     ogf->max_groups[2] = htonl(features->max_groups[2]);
6390     ogf->max_groups[3] = htonl(features->max_groups[3]);
6391     ogf->actions[0] = htonl(features->actions[0]);
6392     ogf->actions[1] = htonl(features->actions[1]);
6393     ogf->actions[2] = htonl(features->actions[2]);
6394     ogf->actions[3] = htonl(features->actions[3]);
6395
6396     return reply;
6397 }
6398
6399 /* Decodes group features reply 'oh' into 'features'. */
6400 void
6401 ofputil_decode_group_features_reply(const struct ofp_header *oh,
6402                                     struct ofputil_group_features *features)
6403 {
6404     const struct ofp12_group_features_stats *ogf = ofpmsg_body(oh);
6405
6406     features->types = ntohl(ogf->types);
6407     features->capabilities = ntohl(ogf->capabilities);
6408     features->max_groups[0] = ntohl(ogf->max_groups[0]);
6409     features->max_groups[1] = ntohl(ogf->max_groups[1]);
6410     features->max_groups[2] = ntohl(ogf->max_groups[2]);
6411     features->max_groups[3] = ntohl(ogf->max_groups[3]);
6412     features->actions[0] = ntohl(ogf->actions[0]);
6413     features->actions[1] = ntohl(ogf->actions[1]);
6414     features->actions[2] = ntohl(ogf->actions[2]);
6415     features->actions[3] = ntohl(ogf->actions[3]);
6416 }
6417
6418 /* Parse a group status request message into a 32 bit OpenFlow 1.1
6419  * group ID and stores the latter in '*group_id'.
6420  * Returns 0 if successful, otherwise an OFPERR_* number. */
6421 enum ofperr
6422 ofputil_decode_group_stats_request(const struct ofp_header *request,
6423                                    uint32_t *group_id)
6424 {
6425     const struct ofp11_group_stats_request *gsr11 = ofpmsg_body(request);
6426     *group_id = ntohl(gsr11->group_id);
6427     return 0;
6428 }
6429
6430 /* Converts a group stats reply in 'msg' into an abstract ofputil_group_stats
6431  * in 'gs'.  Assigns freshly allocated memory to gs->bucket_stats for the
6432  * caller to eventually free.
6433  *
6434  * Multiple group stats replies can be packed into a single OpenFlow message.
6435  * Calling this function multiple times for a single 'msg' iterates through the
6436  * replies.  The caller must initially leave 'msg''s layer pointers null and
6437  * not modify them between calls.
6438  *
6439  * Returns 0 if successful, EOF if no replies were left in this 'msg',
6440  * otherwise a positive errno value. */
6441 int
6442 ofputil_decode_group_stats_reply(struct ofpbuf *msg,
6443                                  struct ofputil_group_stats *gs)
6444 {
6445     struct ofp11_bucket_counter *obc;
6446     struct ofp11_group_stats *ogs11;
6447     enum ofpraw raw;
6448     enum ofperr error;
6449     size_t base_len;
6450     size_t length;
6451     size_t i;
6452
6453     gs->bucket_stats = NULL;
6454     error = (msg->l2
6455              ? ofpraw_decode(&raw, msg->l2)
6456              : ofpraw_pull(&raw, msg));
6457     if (error) {
6458         return error;
6459     }
6460
6461     if (!ofpbuf_size(msg)) {
6462         return EOF;
6463     }
6464
6465     if (raw == OFPRAW_OFPST11_GROUP_REPLY) {
6466         base_len = sizeof *ogs11;
6467         ogs11 = ofpbuf_try_pull(msg, sizeof *ogs11);
6468         gs->duration_sec = gs->duration_nsec = UINT32_MAX;
6469     } else if (raw == OFPRAW_OFPST13_GROUP_REPLY) {
6470         struct ofp13_group_stats *ogs13;
6471
6472         base_len = sizeof *ogs13;
6473         ogs13 = ofpbuf_try_pull(msg, sizeof *ogs13);
6474         if (ogs13) {
6475             ogs11 = &ogs13->gs;
6476             gs->duration_sec = ntohl(ogs13->duration_sec);
6477             gs->duration_nsec = ntohl(ogs13->duration_nsec);
6478         } else {
6479             ogs11 = NULL;
6480         }
6481     } else {
6482         OVS_NOT_REACHED();
6483     }
6484
6485     if (!ogs11) {
6486         VLOG_WARN_RL(&bad_ofmsg_rl, "%s reply has %"PRIu32" leftover bytes at end",
6487                      ofpraw_get_name(raw), ofpbuf_size(msg));
6488         return OFPERR_OFPBRC_BAD_LEN;
6489     }
6490     length = ntohs(ogs11->length);
6491     if (length < sizeof base_len) {
6492         VLOG_WARN_RL(&bad_ofmsg_rl, "%s reply claims invalid length %"PRIuSIZE,
6493                      ofpraw_get_name(raw), length);
6494         return OFPERR_OFPBRC_BAD_LEN;
6495     }
6496
6497     gs->group_id = ntohl(ogs11->group_id);
6498     gs->ref_count = ntohl(ogs11->ref_count);
6499     gs->packet_count = ntohll(ogs11->packet_count);
6500     gs->byte_count = ntohll(ogs11->byte_count);
6501
6502     gs->n_buckets = (length - base_len) / sizeof *obc;
6503     obc = ofpbuf_try_pull(msg, gs->n_buckets * sizeof *obc);
6504     if (!obc) {
6505         VLOG_WARN_RL(&bad_ofmsg_rl, "%s reply has %"PRIu32" leftover bytes at end",
6506                      ofpraw_get_name(raw), ofpbuf_size(msg));
6507         return OFPERR_OFPBRC_BAD_LEN;
6508     }
6509
6510     gs->bucket_stats = xmalloc(gs->n_buckets * sizeof *gs->bucket_stats);
6511     for (i = 0; i < gs->n_buckets; i++) {
6512         gs->bucket_stats[i].packet_count = ntohll(obc[i].packet_count);
6513         gs->bucket_stats[i].byte_count = ntohll(obc[i].byte_count);
6514     }
6515
6516     return 0;
6517 }
6518
6519 /* Appends a group stats reply that contains the data in 'gds' to those already
6520  * present in the list of ofpbufs in 'replies'.  'replies' should have been
6521  * initialized with ofpmp_init(). */
6522 void
6523 ofputil_append_group_desc_reply(const struct ofputil_group_desc *gds,
6524                                 struct list *buckets,
6525                                 struct list *replies)
6526 {
6527     struct ofpbuf *reply = ofpbuf_from_list(list_back(replies));
6528     struct ofp11_group_desc_stats *ogds;
6529     struct ofputil_bucket *bucket;
6530     size_t start_ogds;
6531     enum ofp_version version = ((struct ofp_header *)ofpbuf_data(reply))->version;
6532
6533     start_ogds = ofpbuf_size(reply);
6534     ofpbuf_put_zeros(reply, sizeof *ogds);
6535     LIST_FOR_EACH (bucket, list_node, buckets) {
6536         struct ofp11_bucket *ob;
6537         size_t start_ob;
6538
6539         start_ob = ofpbuf_size(reply);
6540         ofpbuf_put_zeros(reply, sizeof *ob);
6541         ofpacts_put_openflow_actions(bucket->ofpacts, bucket->ofpacts_len,
6542                                      reply, version);
6543         ob = ofpbuf_at_assert(reply, start_ob, sizeof *ob);
6544         ob->len = htons(ofpbuf_size(reply) - start_ob);
6545         ob->weight = htons(bucket->weight);
6546         ob->watch_port = ofputil_port_to_ofp11(bucket->watch_port);
6547         ob->watch_group = htonl(bucket->watch_group);
6548     }
6549     ogds = ofpbuf_at_assert(reply, start_ogds, sizeof *ogds);
6550     ogds->length = htons(ofpbuf_size(reply) - start_ogds);
6551     ogds->type = gds->type;
6552     ogds->group_id = htonl(gds->group_id);
6553
6554     ofpmp_postappend(replies, start_ogds);
6555 }
6556
6557 static enum ofperr
6558 ofputil_pull_buckets(struct ofpbuf *msg, size_t buckets_length,
6559                      enum ofp_version version, struct list *buckets)
6560 {
6561     struct ofp11_bucket *ob;
6562
6563     list_init(buckets);
6564     while (buckets_length > 0) {
6565         struct ofputil_bucket *bucket;
6566         struct ofpbuf ofpacts;
6567         enum ofperr error;
6568         size_t ob_len;
6569
6570         ob = (buckets_length >= sizeof *ob
6571               ? ofpbuf_try_pull(msg, sizeof *ob)
6572               : NULL);
6573         if (!ob) {
6574             VLOG_WARN_RL(&bad_ofmsg_rl, "buckets end with %"PRIuSIZE" leftover bytes",
6575                          buckets_length);
6576         }
6577
6578         ob_len = ntohs(ob->len);
6579         if (ob_len < sizeof *ob) {
6580             VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message bucket length "
6581                          "%"PRIuSIZE" is not valid", ob_len);
6582             return OFPERR_OFPGMFC_BAD_BUCKET;
6583         } else if (ob_len > buckets_length) {
6584             VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message bucket length "
6585                          "%"PRIuSIZE" exceeds remaining buckets data size %"PRIuSIZE,
6586                          ob_len, buckets_length);
6587             return OFPERR_OFPGMFC_BAD_BUCKET;
6588         }
6589         buckets_length -= ob_len;
6590
6591         ofpbuf_init(&ofpacts, 0);
6592         error = ofpacts_pull_openflow_actions(msg, ob_len - sizeof *ob,
6593                                               version, &ofpacts);
6594         if (error) {
6595             ofpbuf_uninit(&ofpacts);
6596             ofputil_bucket_list_destroy(buckets);
6597             return error;
6598         }
6599
6600         bucket = xzalloc(sizeof *bucket);
6601         bucket->weight = ntohs(ob->weight);
6602         error = ofputil_port_from_ofp11(ob->watch_port, &bucket->watch_port);
6603         if (error) {
6604             ofpbuf_uninit(&ofpacts);
6605             ofputil_bucket_list_destroy(buckets);
6606             return OFPERR_OFPGMFC_BAD_WATCH;
6607         }
6608         bucket->watch_group = ntohl(ob->watch_group);
6609         bucket->ofpacts = ofpbuf_steal_data(&ofpacts);
6610         bucket->ofpacts_len = ofpbuf_size(&ofpacts);
6611         list_push_back(buckets, &bucket->list_node);
6612     }
6613
6614     return 0;
6615 }
6616
6617 /* Converts a group description reply in 'msg' into an abstract
6618  * ofputil_group_desc in 'gd'.
6619  *
6620  * Multiple group description replies can be packed into a single OpenFlow
6621  * message.  Calling this function multiple times for a single 'msg' iterates
6622  * through the replies.  The caller must initially leave 'msg''s layer pointers
6623  * null and not modify them between calls.
6624  *
6625  * Returns 0 if successful, EOF if no replies were left in this 'msg',
6626  * otherwise a positive errno value. */
6627 int
6628 ofputil_decode_group_desc_reply(struct ofputil_group_desc *gd,
6629                                 struct ofpbuf *msg, enum ofp_version version)
6630 {
6631     struct ofp11_group_desc_stats *ogds;
6632     size_t length;
6633
6634     if (!msg->l2) {
6635         ofpraw_pull_assert(msg);
6636     }
6637
6638     if (!ofpbuf_size(msg)) {
6639         return EOF;
6640     }
6641
6642     ogds = ofpbuf_try_pull(msg, sizeof *ogds);
6643     if (!ogds) {
6644         VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST11_GROUP_DESC reply has %"PRIu32" "
6645                      "leftover bytes at end", ofpbuf_size(msg));
6646         return OFPERR_OFPBRC_BAD_LEN;
6647     }
6648     gd->type = ogds->type;
6649     gd->group_id = ntohl(ogds->group_id);
6650
6651     length = ntohs(ogds->length);
6652     if (length < sizeof *ogds || length - sizeof *ogds > ofpbuf_size(msg)) {
6653         VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST11_GROUP_DESC reply claims invalid "
6654                      "length %"PRIuSIZE, length);
6655         return OFPERR_OFPBRC_BAD_LEN;
6656     }
6657
6658     return ofputil_pull_buckets(msg, length - sizeof *ogds, version,
6659                                 &gd->buckets);
6660 }
6661
6662 /* Converts abstract group mod 'gm' into a message for OpenFlow version
6663  * 'ofp_version' and returns the message. */
6664 struct ofpbuf *
6665 ofputil_encode_group_mod(enum ofp_version ofp_version,
6666                          const struct ofputil_group_mod *gm)
6667 {
6668     struct ofpbuf *b;
6669     struct ofp11_group_mod *ogm;
6670     size_t start_ogm;
6671     size_t start_bucket;
6672     struct ofputil_bucket *bucket;
6673     struct ofp11_bucket *ob;
6674
6675     switch (ofp_version) {
6676     case OFP10_VERSION: {
6677         if (gm->command == OFPGC11_ADD) {
6678             ovs_fatal(0, "add-group needs OpenFlow 1.1 or later "
6679                          "(\'-O OpenFlow11\')");
6680         } else if (gm->command == OFPGC11_MODIFY) {
6681             ovs_fatal(0, "mod-group needs OpenFlow 1.1 or later "
6682                          "(\'-O OpenFlow11\')");
6683         } else {
6684             ovs_fatal(0, "del-groups needs OpenFlow 1.1 or later "
6685                          "(\'-O OpenFlow11\')");
6686         }
6687     }
6688
6689     case OFP11_VERSION:
6690     case OFP12_VERSION:
6691     case OFP13_VERSION:
6692     case OFP14_VERSION:
6693         b = ofpraw_alloc(OFPRAW_OFPT11_GROUP_MOD, ofp_version, 0);
6694         start_ogm = ofpbuf_size(b);
6695         ofpbuf_put_zeros(b, sizeof *ogm);
6696
6697         LIST_FOR_EACH (bucket, list_node, &gm->buckets) {
6698             start_bucket = ofpbuf_size(b);
6699             ofpbuf_put_zeros(b, sizeof *ob);
6700             if (bucket->ofpacts && bucket->ofpacts_len) {
6701                 ofpacts_put_openflow_actions(bucket->ofpacts,
6702                                              bucket->ofpacts_len, b,
6703                                              ofp_version);
6704             }
6705             ob = ofpbuf_at_assert(b, start_bucket, sizeof *ob);
6706             ob->len = htons(ofpbuf_size(b) - start_bucket);;
6707             ob->weight = htons(bucket->weight);
6708             ob->watch_port = ofputil_port_to_ofp11(bucket->watch_port);
6709             ob->watch_group = htonl(bucket->watch_group);
6710         }
6711         ogm = ofpbuf_at_assert(b, start_ogm, sizeof *ogm);
6712         ogm->command = htons(gm->command);
6713         ogm->type = gm->type;
6714         ogm->group_id = htonl(gm->group_id);
6715
6716         break;
6717
6718     default:
6719         OVS_NOT_REACHED();
6720     }
6721
6722     return b;
6723 }
6724
6725 /* Converts OpenFlow group mod message 'oh' into an abstract group mod in
6726  * 'gm'.  Returns 0 if successful, otherwise an OpenFlow error code. */
6727 enum ofperr
6728 ofputil_decode_group_mod(const struct ofp_header *oh,
6729                          struct ofputil_group_mod *gm)
6730 {
6731     const struct ofp11_group_mod *ogm;
6732     struct ofpbuf msg;
6733     struct ofputil_bucket *bucket;
6734     enum ofperr err;
6735
6736     ofpbuf_use_const(&msg, oh, ntohs(oh->length));
6737     ofpraw_pull_assert(&msg);
6738
6739     ogm = ofpbuf_pull(&msg, sizeof *ogm);
6740     gm->command = ntohs(ogm->command);
6741     gm->type = ogm->type;
6742     gm->group_id = ntohl(ogm->group_id);
6743
6744     err = ofputil_pull_buckets(&msg, ofpbuf_size(&msg), oh->version, &gm->buckets);
6745     if (err) {
6746         return err;
6747     }
6748
6749     LIST_FOR_EACH (bucket, list_node, &gm->buckets) {
6750         switch (gm->type) {
6751         case OFPGT11_ALL:
6752         case OFPGT11_INDIRECT:
6753             if (ofputil_bucket_has_liveness(bucket)) {
6754                 return OFPERR_OFPGMFC_WATCH_UNSUPPORTED;
6755             }
6756             break;
6757         case OFPGT11_SELECT:
6758             break;
6759         case OFPGT11_FF:
6760             if (!ofputil_bucket_has_liveness(bucket)) {
6761                 return OFPERR_OFPGMFC_INVALID_GROUP;
6762             }
6763             break;
6764         default:
6765             OVS_NOT_REACHED();
6766         }
6767     }
6768
6769     return 0;
6770 }
6771
6772 /* Parse a queue status request message into 'oqsr'.
6773  * Returns 0 if successful, otherwise an OFPERR_* number. */
6774 enum ofperr
6775 ofputil_decode_queue_stats_request(const struct ofp_header *request,
6776                                    struct ofputil_queue_stats_request *oqsr)
6777 {
6778     switch ((enum ofp_version)request->version) {
6779     case OFP14_VERSION:
6780     case OFP13_VERSION:
6781     case OFP12_VERSION:
6782     case OFP11_VERSION: {
6783         const struct ofp11_queue_stats_request *qsr11 = ofpmsg_body(request);
6784         oqsr->queue_id = ntohl(qsr11->queue_id);
6785         return ofputil_port_from_ofp11(qsr11->port_no, &oqsr->port_no);
6786     }
6787
6788     case OFP10_VERSION: {
6789         const struct ofp10_queue_stats_request *qsr10 = ofpmsg_body(request);
6790         oqsr->queue_id = ntohl(qsr10->queue_id);
6791         oqsr->port_no = u16_to_ofp(ntohs(qsr10->port_no));
6792         /* OF 1.0 uses OFPP_ALL for OFPP_ANY */
6793         if (oqsr->port_no == OFPP_ALL) {
6794             oqsr->port_no = OFPP_ANY;
6795         }
6796         return 0;
6797     }
6798
6799     default:
6800         OVS_NOT_REACHED();
6801     }
6802 }
6803
6804 /* Encode a queue statsrequest for 'oqsr', the encoded message
6805  * will be fore Open Flow version 'ofp_version'. Returns message
6806  * as a struct ofpbuf. Returns encoded message on success, NULL on error */
6807 struct ofpbuf *
6808 ofputil_encode_queue_stats_request(enum ofp_version ofp_version,
6809                                    const struct ofputil_queue_stats_request *oqsr)
6810 {
6811     struct ofpbuf *request;
6812
6813     switch (ofp_version) {
6814     case OFP11_VERSION:
6815     case OFP12_VERSION:
6816     case OFP13_VERSION:
6817     case OFP14_VERSION: {
6818         struct ofp11_queue_stats_request *req;
6819         request = ofpraw_alloc(OFPRAW_OFPST11_QUEUE_REQUEST, ofp_version, 0);
6820         req = ofpbuf_put_zeros(request, sizeof *req);
6821         req->port_no = ofputil_port_to_ofp11(oqsr->port_no);
6822         req->queue_id = htonl(oqsr->queue_id);
6823         break;
6824     }
6825     case OFP10_VERSION: {
6826         struct ofp10_queue_stats_request *req;
6827         request = ofpraw_alloc(OFPRAW_OFPST10_QUEUE_REQUEST, ofp_version, 0);
6828         req = ofpbuf_put_zeros(request, sizeof *req);
6829         /* OpenFlow 1.0 needs OFPP_ALL instead of OFPP_ANY */
6830         req->port_no = htons(ofp_to_u16(oqsr->port_no == OFPP_ANY
6831                                         ? OFPP_ALL : oqsr->port_no));
6832         req->queue_id = htonl(oqsr->queue_id);
6833         break;
6834     }
6835     default:
6836         OVS_NOT_REACHED();
6837     }
6838
6839     return request;
6840 }
6841
6842 static size_t
6843 ofputil_get_queue_stats_size(enum ofp_version ofp_version)
6844 {
6845     switch (ofp_version) {
6846     case OFP10_VERSION:
6847         return sizeof(struct ofp10_queue_stats);
6848     case OFP11_VERSION:
6849     case OFP12_VERSION:
6850         return sizeof(struct ofp11_queue_stats);
6851     case OFP13_VERSION:
6852         return sizeof(struct ofp13_queue_stats);
6853     case OFP14_VERSION:
6854         OVS_NOT_REACHED();
6855         return 0;
6856     default:
6857         OVS_NOT_REACHED();
6858     }
6859 }
6860
6861 /* Returns the number of queue stats elements in OFPTYPE_QUEUE_STATS_REPLY
6862  * message 'oh'. */
6863 size_t
6864 ofputil_count_queue_stats(const struct ofp_header *oh)
6865 {
6866     struct ofpbuf b;
6867
6868     ofpbuf_use_const(&b, oh, ntohs(oh->length));
6869     ofpraw_pull_assert(&b);
6870
6871     return ofpbuf_size(&b) / ofputil_get_queue_stats_size(oh->version);
6872 }
6873
6874 static enum ofperr
6875 ofputil_queue_stats_from_ofp10(struct ofputil_queue_stats *oqs,
6876                                const struct ofp10_queue_stats *qs10)
6877 {
6878     oqs->port_no = u16_to_ofp(ntohs(qs10->port_no));
6879     oqs->queue_id = ntohl(qs10->queue_id);
6880     oqs->tx_bytes = ntohll(get_32aligned_be64(&qs10->tx_bytes));
6881     oqs->tx_packets = ntohll(get_32aligned_be64(&qs10->tx_packets));
6882     oqs->tx_errors = ntohll(get_32aligned_be64(&qs10->tx_errors));
6883     oqs->duration_sec = oqs->duration_nsec = UINT32_MAX;
6884
6885     return 0;
6886 }
6887
6888 static enum ofperr
6889 ofputil_queue_stats_from_ofp11(struct ofputil_queue_stats *oqs,
6890                                const struct ofp11_queue_stats *qs11)
6891 {
6892     enum ofperr error;
6893
6894     error = ofputil_port_from_ofp11(qs11->port_no, &oqs->port_no);
6895     if (error) {
6896         return error;
6897     }
6898
6899     oqs->queue_id = ntohl(qs11->queue_id);
6900     oqs->tx_bytes = ntohll(qs11->tx_bytes);
6901     oqs->tx_packets = ntohll(qs11->tx_packets);
6902     oqs->tx_errors = ntohll(qs11->tx_errors);
6903     oqs->duration_sec = oqs->duration_nsec = UINT32_MAX;
6904
6905     return 0;
6906 }
6907
6908 static enum ofperr
6909 ofputil_queue_stats_from_ofp13(struct ofputil_queue_stats *oqs,
6910                                const struct ofp13_queue_stats *qs13)
6911 {
6912     enum ofperr error = ofputil_queue_stats_from_ofp11(oqs, &qs13->qs);
6913     if (!error) {
6914         oqs->duration_sec = ntohl(qs13->duration_sec);
6915         oqs->duration_nsec = ntohl(qs13->duration_nsec);
6916     }
6917
6918     return error;
6919 }
6920
6921 /* Converts an OFPST_QUEUE_STATS reply in 'msg' into an abstract
6922  * ofputil_queue_stats in 'qs'.
6923  *
6924  * Multiple OFPST_QUEUE_STATS replies can be packed into a single OpenFlow
6925  * message.  Calling this function multiple times for a single 'msg' iterates
6926  * through the replies.  The caller must initially leave 'msg''s layer pointers
6927  * null and not modify them between calls.
6928  *
6929  * Returns 0 if successful, EOF if no replies were left in this 'msg',
6930  * otherwise a positive errno value. */
6931 int
6932 ofputil_decode_queue_stats(struct ofputil_queue_stats *qs, struct ofpbuf *msg)
6933 {
6934     enum ofperr error;
6935     enum ofpraw raw;
6936
6937     error = (msg->l2
6938              ? ofpraw_decode(&raw, msg->l2)
6939              : ofpraw_pull(&raw, msg));
6940     if (error) {
6941         return error;
6942     }
6943
6944     if (!ofpbuf_size(msg)) {
6945         return EOF;
6946     } else if (raw == OFPRAW_OFPST13_QUEUE_REPLY) {
6947         const struct ofp13_queue_stats *qs13;
6948
6949         qs13 = ofpbuf_try_pull(msg, sizeof *qs13);
6950         if (!qs13) {
6951             goto bad_len;
6952         }
6953         return ofputil_queue_stats_from_ofp13(qs, qs13);
6954     } else if (raw == OFPRAW_OFPST11_QUEUE_REPLY) {
6955         const struct ofp11_queue_stats *qs11;
6956
6957         qs11 = ofpbuf_try_pull(msg, sizeof *qs11);
6958         if (!qs11) {
6959             goto bad_len;
6960         }
6961         return ofputil_queue_stats_from_ofp11(qs, qs11);
6962     } else if (raw == OFPRAW_OFPST10_QUEUE_REPLY) {
6963         const struct ofp10_queue_stats *qs10;
6964
6965         qs10 = ofpbuf_try_pull(msg, sizeof *qs10);
6966         if (!qs10) {
6967             goto bad_len;
6968         }
6969         return ofputil_queue_stats_from_ofp10(qs, qs10);
6970     } else {
6971         OVS_NOT_REACHED();
6972     }
6973
6974  bad_len:
6975     VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_QUEUE reply has %"PRIu32" leftover "
6976                  "bytes at end", ofpbuf_size(msg));
6977     return OFPERR_OFPBRC_BAD_LEN;
6978 }
6979
6980 static void
6981 ofputil_queue_stats_to_ofp10(const struct ofputil_queue_stats *oqs,
6982                              struct ofp10_queue_stats *qs10)
6983 {
6984     qs10->port_no = htons(ofp_to_u16(oqs->port_no));
6985     memset(qs10->pad, 0, sizeof qs10->pad);
6986     qs10->queue_id = htonl(oqs->queue_id);
6987     put_32aligned_be64(&qs10->tx_bytes, htonll(oqs->tx_bytes));
6988     put_32aligned_be64(&qs10->tx_packets, htonll(oqs->tx_packets));
6989     put_32aligned_be64(&qs10->tx_errors, htonll(oqs->tx_errors));
6990 }
6991
6992 static void
6993 ofputil_queue_stats_to_ofp11(const struct ofputil_queue_stats *oqs,
6994                              struct ofp11_queue_stats *qs11)
6995 {
6996     qs11->port_no = ofputil_port_to_ofp11(oqs->port_no);
6997     qs11->queue_id = htonl(oqs->queue_id);
6998     qs11->tx_bytes = htonll(oqs->tx_bytes);
6999     qs11->tx_packets = htonll(oqs->tx_packets);
7000     qs11->tx_errors = htonll(oqs->tx_errors);
7001 }
7002
7003 static void
7004 ofputil_queue_stats_to_ofp13(const struct ofputil_queue_stats *oqs,
7005                              struct ofp13_queue_stats *qs13)
7006 {
7007     ofputil_queue_stats_to_ofp11(oqs, &qs13->qs);
7008     if (oqs->duration_sec != UINT32_MAX) {
7009         qs13->duration_sec = htonl(oqs->duration_sec);
7010         qs13->duration_nsec = htonl(oqs->duration_nsec);
7011     } else {
7012         qs13->duration_sec = OVS_BE32_MAX;
7013         qs13->duration_nsec = OVS_BE32_MAX;
7014     }
7015 }
7016
7017 /* Encode a queue stat for 'oqs' and append it to 'replies'. */
7018 void
7019 ofputil_append_queue_stat(struct list *replies,
7020                           const struct ofputil_queue_stats *oqs)
7021 {
7022     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
7023     struct ofp_header *oh = ofpbuf_data(msg);
7024
7025     switch ((enum ofp_version)oh->version) {
7026     case OFP13_VERSION: {
7027         struct ofp13_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
7028         ofputil_queue_stats_to_ofp13(oqs, reply);
7029         break;
7030     }
7031
7032     case OFP12_VERSION:
7033     case OFP11_VERSION: {
7034         struct ofp11_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
7035         ofputil_queue_stats_to_ofp11(oqs, reply);
7036         break;
7037     }
7038
7039     case OFP10_VERSION: {
7040         struct ofp10_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
7041         ofputil_queue_stats_to_ofp10(oqs, reply);
7042         break;
7043     }
7044
7045     case OFP14_VERSION:
7046         OVS_NOT_REACHED();
7047         break;
7048
7049     default:
7050         OVS_NOT_REACHED();
7051     }
7052 }