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