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