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