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