Replace most uses of assert by ovs_assert.
[sliver-openvswitch.git] / lib / ofp-util.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "ofp-print.h"
19 #include <ctype.h>
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <sys/types.h>
23 #include <netinet/in.h>
24 #include <netinet/icmp6.h>
25 #include <stdlib.h>
26 #include "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     ovs_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     /* skb_mark and skb_priority can't be sent in a flow_mod */
1071     if (wc->masks.skb_mark || wc->masks.skb_priority) {
1072         return OFPUTIL_P_NONE;
1073     }
1074
1075     /* NXM, OXM, and OF1.1 support bitwise matching on ethernet addresses. */
1076     if (!eth_mask_is_exact(wc->masks.dl_src)
1077         && !eth_addr_is_zero(wc->masks.dl_src)) {
1078         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1079             | OFPUTIL_P_OF13_OXM;
1080     }
1081     if (!eth_mask_is_exact(wc->masks.dl_dst)
1082         && !eth_addr_is_zero(wc->masks.dl_dst)) {
1083         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1084             | OFPUTIL_P_OF13_OXM;
1085     }
1086
1087     /* NXM, OXM, and OF1.1+ support matching metadata. */
1088     if (wc->masks.metadata != htonll(0)) {
1089         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1090             | OFPUTIL_P_OF13_OXM;
1091     }
1092
1093     /* NXM and OXM support matching ARP hardware addresses. */
1094     if (!eth_addr_is_zero(wc->masks.arp_sha) ||
1095         !eth_addr_is_zero(wc->masks.arp_tha)) {
1096         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1097             | OFPUTIL_P_OF13_OXM;
1098     }
1099
1100     /* NXM and OXM support matching IPv6 traffic. */
1101     if (match->flow.dl_type == htons(ETH_TYPE_IPV6)) {
1102         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1103             | OFPUTIL_P_OF13_OXM;
1104     }
1105
1106     /* NXM and OXM support matching registers. */
1107     if (!regs_fully_wildcarded(wc)) {
1108         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1109             | OFPUTIL_P_OF13_OXM;
1110     }
1111
1112     /* NXM and OXM support matching tun_id. */
1113     if (wc->masks.tunnel.tun_id != htonll(0)) {
1114         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1115             | OFPUTIL_P_OF13_OXM;
1116     }
1117
1118     /* NXM and OXM support matching fragments. */
1119     if (wc->masks.nw_frag) {
1120         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1121             | OFPUTIL_P_OF13_OXM;
1122     }
1123
1124     /* NXM and OXM support matching IPv6 flow label. */
1125     if (wc->masks.ipv6_label) {
1126         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1127             | OFPUTIL_P_OF13_OXM;
1128     }
1129
1130     /* NXM and OXM support matching IP ECN bits. */
1131     if (wc->masks.nw_tos & IP_ECN_MASK) {
1132         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1133             | OFPUTIL_P_OF13_OXM;
1134     }
1135
1136     /* NXM and OXM support matching IP TTL/hop limit. */
1137     if (wc->masks.nw_ttl) {
1138         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1139             | OFPUTIL_P_OF13_OXM;
1140     }
1141
1142     /* NXM and OXM support non-CIDR IPv4 address masks. */
1143     if (!ip_is_cidr(wc->masks.nw_src) || !ip_is_cidr(wc->masks.nw_dst)) {
1144         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1145             | OFPUTIL_P_OF13_OXM;
1146     }
1147
1148     /* NXM and OXM support bitwise matching on transport port. */
1149     if ((wc->masks.tp_src && wc->masks.tp_src != htons(UINT16_MAX)) ||
1150         (wc->masks.tp_dst && wc->masks.tp_dst != htons(UINT16_MAX))) {
1151         return OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1152             | OFPUTIL_P_OF13_OXM;
1153     }
1154
1155     /* Other formats can express this rule. */
1156     return OFPUTIL_P_ANY;
1157 }
1158
1159 void
1160 ofputil_format_version(struct ds *msg, enum ofp_version version)
1161 {
1162     ds_put_format(msg, "0x%02x", version);
1163 }
1164
1165 void
1166 ofputil_format_version_name(struct ds *msg, enum ofp_version version)
1167 {
1168     ds_put_cstr(msg, ofputil_version_to_string(version));
1169 }
1170
1171 static void
1172 ofputil_format_version_bitmap__(struct ds *msg, uint32_t bitmap,
1173                                 void (*format_version)(struct ds *msg,
1174                                                        enum ofp_version))
1175 {
1176     while (bitmap) {
1177         format_version(msg, raw_ctz(bitmap));
1178         bitmap = zero_rightmost_1bit(bitmap);
1179         if (bitmap) {
1180             ds_put_cstr(msg, ", ");
1181         }
1182     }
1183 }
1184
1185 void
1186 ofputil_format_version_bitmap(struct ds *msg, uint32_t bitmap)
1187 {
1188     ofputil_format_version_bitmap__(msg, bitmap, ofputil_format_version);
1189 }
1190
1191 void
1192 ofputil_format_version_bitmap_names(struct ds *msg, uint32_t bitmap)
1193 {
1194     ofputil_format_version_bitmap__(msg, bitmap, ofputil_format_version_name);
1195 }
1196
1197 static bool
1198 ofputil_decode_hello_bitmap(const struct ofp_hello_elem_header *oheh,
1199                             uint32_t *allowed_versionsp)
1200 {
1201     uint16_t bitmap_len = ntohs(oheh->length) - sizeof *oheh;
1202     const ovs_be32 *bitmap = (const ovs_be32 *) (oheh + 1);
1203     uint32_t allowed_versions;
1204
1205     if (!bitmap_len || bitmap_len % sizeof *bitmap) {
1206         return false;
1207     }
1208
1209     /* Only use the first 32-bit element of the bitmap as that is all the
1210      * current implementation supports.  Subsequent elements are ignored which
1211      * should have no effect on session negotiation until Open vSwtich supports
1212      * wire-protocol versions greater than 31.
1213      */
1214     allowed_versions = ntohl(bitmap[0]);
1215
1216     if (allowed_versions & 1) {
1217         /* There's no OpenFlow version 0. */
1218         VLOG_WARN_RL(&bad_ofmsg_rl, "peer claims to support invalid OpenFlow "
1219                      "version 0x00");
1220         allowed_versions &= ~1u;
1221     }
1222
1223     if (!allowed_versions) {
1224         VLOG_WARN_RL(&bad_ofmsg_rl, "peer does not support any OpenFlow "
1225                      "version (between 0x01 and 0x1f)");
1226         return false;
1227     }
1228
1229     *allowed_versionsp = allowed_versions;
1230     return true;
1231 }
1232
1233 static uint32_t
1234 version_bitmap_from_version(uint8_t ofp_version)
1235 {
1236     return ((ofp_version < 32 ? 1u << ofp_version : 0) - 1) << 1;
1237 }
1238
1239 /* Decodes OpenFlow OFPT_HELLO message 'oh', storing into '*allowed_versions'
1240  * the set of OpenFlow versions for which 'oh' announces support.
1241  *
1242  * Because of how OpenFlow defines OFPT_HELLO messages, this function is always
1243  * successful, and thus '*allowed_versions' is always initialized.  However, it
1244  * returns false if 'oh' contains some data that could not be fully understood,
1245  * true if 'oh' was completely parsed. */
1246 bool
1247 ofputil_decode_hello(const struct ofp_header *oh, uint32_t *allowed_versions)
1248 {
1249     struct ofpbuf msg;
1250     bool ok = true;
1251
1252     ofpbuf_use_const(&msg, oh, ntohs(oh->length));
1253     ofpbuf_pull(&msg, sizeof *oh);
1254
1255     *allowed_versions = version_bitmap_from_version(oh->version);
1256     while (msg.size) {
1257         const struct ofp_hello_elem_header *oheh;
1258         unsigned int len;
1259
1260         if (msg.size < sizeof *oheh) {
1261             return false;
1262         }
1263
1264         oheh = msg.data;
1265         len = ntohs(oheh->length);
1266         if (len < sizeof *oheh || !ofpbuf_try_pull(&msg, ROUND_UP(len, 8))) {
1267             return false;
1268         }
1269
1270         if (oheh->type != htons(OFPHET_VERSIONBITMAP)
1271             || !ofputil_decode_hello_bitmap(oheh, allowed_versions)) {
1272             ok = false;
1273         }
1274     }
1275
1276     return ok;
1277 }
1278
1279 /* Returns true if 'allowed_versions' needs to be accompanied by a version
1280  * bitmap to be correctly expressed in an OFPT_HELLO message. */
1281 static inline bool
1282 should_send_version_bitmap(uint32_t allowed_versions)
1283 {
1284     return !is_pow2((allowed_versions >> 1) + 1);
1285 }
1286
1287 /* Create an OFPT_HELLO message that expresses support for the OpenFlow
1288  * versions in the 'allowed_versions' bitmaps and returns the message. */
1289 struct ofpbuf *
1290 ofputil_encode_hello(uint32_t allowed_versions)
1291 {
1292     enum ofp_version ofp_version;
1293     struct ofpbuf *msg;
1294
1295     ofp_version = leftmost_1bit_idx(allowed_versions);
1296     msg = ofpraw_alloc(OFPRAW_OFPT_HELLO, ofp_version, 0);
1297
1298     if (should_send_version_bitmap(allowed_versions)) {
1299         struct ofp_hello_elem_header *oheh;
1300         uint16_t map_len;
1301
1302         map_len = sizeof allowed_versions;
1303         oheh = ofpbuf_put_zeros(msg, ROUND_UP(map_len + sizeof *oheh, 8));
1304         oheh->type = htons(OFPHET_VERSIONBITMAP);
1305         oheh->length = htons(map_len + sizeof *oheh);
1306         *(ovs_be32 *)(oheh + 1) = htonl(allowed_versions);
1307
1308         ofpmsg_update_length(msg);
1309     }
1310
1311     return msg;
1312 }
1313
1314 /* Returns an OpenFlow message that, sent on an OpenFlow connection whose
1315  * protocol is 'current', at least partly transitions the protocol to 'want'.
1316  * Stores in '*next' the protocol that will be in effect on the OpenFlow
1317  * connection if the switch processes the returned message correctly.  (If
1318  * '*next != want' then the caller will have to iterate.)
1319  *
1320  * If 'current == want', or if it is not possible to transition from 'current'
1321  * to 'want' (because, for example, 'current' and 'want' use different OpenFlow
1322  * protocol versions), returns NULL and stores 'current' in '*next'. */
1323 struct ofpbuf *
1324 ofputil_encode_set_protocol(enum ofputil_protocol current,
1325                             enum ofputil_protocol want,
1326                             enum ofputil_protocol *next)
1327 {
1328     enum ofp_version cur_version, want_version;
1329     enum ofputil_protocol cur_base, want_base;
1330     bool cur_tid, want_tid;
1331
1332     cur_version = ofputil_protocol_to_ofp_version(current);
1333     want_version = ofputil_protocol_to_ofp_version(want);
1334     if (cur_version != want_version) {
1335         *next = current;
1336         return NULL;
1337     }
1338
1339     cur_base = ofputil_protocol_to_base(current);
1340     want_base = ofputil_protocol_to_base(want);
1341     if (cur_base != want_base) {
1342         *next = ofputil_protocol_set_base(current, want_base);
1343
1344         switch (want_base) {
1345         case OFPUTIL_P_OF10_NXM:
1346             return ofputil_encode_nx_set_flow_format(NXFF_NXM);
1347
1348         case OFPUTIL_P_OF10_STD:
1349             return ofputil_encode_nx_set_flow_format(NXFF_OPENFLOW10);
1350
1351         case OFPUTIL_P_OF12_OXM:
1352         case OFPUTIL_P_OF13_OXM:
1353             /* There are only one of each OpenFlow 1.2+ protocols and we already
1354              * verified above that we're not trying to change versions. */
1355             NOT_REACHED();
1356
1357         case OFPUTIL_P_OF10_STD_TID:
1358         case OFPUTIL_P_OF10_NXM_TID:
1359             NOT_REACHED();
1360         }
1361     }
1362
1363     cur_tid = (current & OFPUTIL_P_TID) != 0;
1364     want_tid = (want & OFPUTIL_P_TID) != 0;
1365     if (cur_tid != want_tid) {
1366         *next = ofputil_protocol_set_tid(current, want_tid);
1367         return ofputil_make_flow_mod_table_id(want_tid);
1368     }
1369
1370     ovs_assert(current == want);
1371
1372     *next = current;
1373     return NULL;
1374 }
1375
1376 /* Returns an NXT_SET_FLOW_FORMAT message that can be used to set the flow
1377  * format to 'nxff'.  */
1378 struct ofpbuf *
1379 ofputil_encode_nx_set_flow_format(enum nx_flow_format nxff)
1380 {
1381     struct nx_set_flow_format *sff;
1382     struct ofpbuf *msg;
1383
1384     ovs_assert(ofputil_nx_flow_format_is_valid(nxff));
1385
1386     msg = ofpraw_alloc(OFPRAW_NXT_SET_FLOW_FORMAT, OFP10_VERSION, 0);
1387     sff = ofpbuf_put_zeros(msg, sizeof *sff);
1388     sff->format = htonl(nxff);
1389
1390     return msg;
1391 }
1392
1393 /* Returns the base protocol if 'flow_format' is a valid NXFF_* value, false
1394  * otherwise. */
1395 enum ofputil_protocol
1396 ofputil_nx_flow_format_to_protocol(enum nx_flow_format flow_format)
1397 {
1398     switch (flow_format) {
1399     case NXFF_OPENFLOW10:
1400         return OFPUTIL_P_OF10_STD;
1401
1402     case NXFF_NXM:
1403         return OFPUTIL_P_OF10_NXM;
1404
1405     default:
1406         return 0;
1407     }
1408 }
1409
1410 /* Returns true if 'flow_format' is a valid NXFF_* value, false otherwise. */
1411 bool
1412 ofputil_nx_flow_format_is_valid(enum nx_flow_format flow_format)
1413 {
1414     return ofputil_nx_flow_format_to_protocol(flow_format) != 0;
1415 }
1416
1417 /* Returns a string version of 'flow_format', which must be a valid NXFF_*
1418  * value. */
1419 const char *
1420 ofputil_nx_flow_format_to_string(enum nx_flow_format flow_format)
1421 {
1422     switch (flow_format) {
1423     case NXFF_OPENFLOW10:
1424         return "openflow10";
1425     case NXFF_NXM:
1426         return "nxm";
1427     default:
1428         NOT_REACHED();
1429     }
1430 }
1431
1432 struct ofpbuf *
1433 ofputil_make_set_packet_in_format(enum ofp_version ofp_version,
1434                                   enum nx_packet_in_format packet_in_format)
1435 {
1436     struct nx_set_packet_in_format *spif;
1437     struct ofpbuf *msg;
1438
1439     msg = ofpraw_alloc(OFPRAW_NXT_SET_PACKET_IN_FORMAT, ofp_version, 0);
1440     spif = ofpbuf_put_zeros(msg, sizeof *spif);
1441     spif->format = htonl(packet_in_format);
1442
1443     return msg;
1444 }
1445
1446 /* Returns an OpenFlow message that can be used to turn the flow_mod_table_id
1447  * extension on or off (according to 'flow_mod_table_id'). */
1448 struct ofpbuf *
1449 ofputil_make_flow_mod_table_id(bool flow_mod_table_id)
1450 {
1451     struct nx_flow_mod_table_id *nfmti;
1452     struct ofpbuf *msg;
1453
1454     msg = ofpraw_alloc(OFPRAW_NXT_FLOW_MOD_TABLE_ID, OFP10_VERSION, 0);
1455     nfmti = ofpbuf_put_zeros(msg, sizeof *nfmti);
1456     nfmti->set = flow_mod_table_id;
1457     return msg;
1458 }
1459
1460 /* Converts an OFPT_FLOW_MOD or NXT_FLOW_MOD message 'oh' into an abstract
1461  * flow_mod in 'fm'.  Returns 0 if successful, otherwise an OpenFlow error
1462  * code.
1463  *
1464  * Uses 'ofpacts' to store the abstract OFPACT_* version of 'oh''s actions.
1465  * The caller must initialize 'ofpacts' and retains ownership of it.
1466  * 'fm->ofpacts' will point into the 'ofpacts' buffer.
1467  *
1468  * Does not validate the flow_mod actions.  The caller should do that, with
1469  * ofpacts_check(). */
1470 enum ofperr
1471 ofputil_decode_flow_mod(struct ofputil_flow_mod *fm,
1472                         const struct ofp_header *oh,
1473                         enum ofputil_protocol protocol,
1474                         struct ofpbuf *ofpacts)
1475 {
1476     uint16_t command;
1477     struct ofpbuf b;
1478     enum ofpraw raw;
1479
1480     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1481     raw = ofpraw_pull_assert(&b);
1482     if (raw == OFPRAW_OFPT11_FLOW_MOD) {
1483         /* Standard OpenFlow 1.1 flow_mod. */
1484         const struct ofp11_flow_mod *ofm;
1485         enum ofperr error;
1486
1487         ofm = ofpbuf_pull(&b, sizeof *ofm);
1488
1489         error = ofputil_pull_ofp11_match(&b, &fm->match, NULL);
1490         if (error) {
1491             return error;
1492         }
1493
1494         error = ofpacts_pull_openflow11_instructions(&b, b.size, ofpacts);
1495         if (error) {
1496             return error;
1497         }
1498
1499         /* Translate the message. */
1500         fm->priority = ntohs(ofm->priority);
1501         if (ofm->command == OFPFC_ADD) {
1502             fm->cookie = htonll(0);
1503             fm->cookie_mask = htonll(0);
1504             fm->new_cookie = ofm->cookie;
1505         } else {
1506             fm->cookie = ofm->cookie;
1507             fm->cookie_mask = ofm->cookie_mask;
1508             fm->new_cookie = htonll(UINT64_MAX);
1509         }
1510         fm->command = ofm->command;
1511         fm->table_id = ofm->table_id;
1512         fm->idle_timeout = ntohs(ofm->idle_timeout);
1513         fm->hard_timeout = ntohs(ofm->hard_timeout);
1514         fm->buffer_id = ntohl(ofm->buffer_id);
1515         error = ofputil_port_from_ofp11(ofm->out_port, &fm->out_port);
1516         if (error) {
1517             return error;
1518         }
1519         if ((ofm->command == OFPFC_DELETE
1520              || ofm->command == OFPFC_DELETE_STRICT)
1521             && ofm->out_group != htonl(OFPG_ANY)) {
1522             return OFPERR_OFPFMFC_UNKNOWN;
1523         }
1524         fm->flags = ntohs(ofm->flags);
1525     } else {
1526         if (raw == OFPRAW_OFPT10_FLOW_MOD) {
1527             /* Standard OpenFlow 1.0 flow_mod. */
1528             const struct ofp10_flow_mod *ofm;
1529             enum ofperr error;
1530
1531             /* Get the ofp10_flow_mod. */
1532             ofm = ofpbuf_pull(&b, sizeof *ofm);
1533
1534             /* Translate the rule. */
1535             ofputil_match_from_ofp10_match(&ofm->match, &fm->match);
1536             ofputil_normalize_match(&fm->match);
1537
1538             /* Now get the actions. */
1539             error = ofpacts_pull_openflow10(&b, b.size, ofpacts);
1540             if (error) {
1541                 return error;
1542             }
1543
1544             /* OpenFlow 1.0 says that exact-match rules have to have the
1545              * highest possible priority. */
1546             fm->priority = (ofm->match.wildcards & htonl(OFPFW10_ALL)
1547                             ? ntohs(ofm->priority)
1548                             : UINT16_MAX);
1549
1550             /* Translate the message. */
1551             command = ntohs(ofm->command);
1552             fm->cookie = htonll(0);
1553             fm->cookie_mask = htonll(0);
1554             fm->new_cookie = ofm->cookie;
1555             fm->idle_timeout = ntohs(ofm->idle_timeout);
1556             fm->hard_timeout = ntohs(ofm->hard_timeout);
1557             fm->buffer_id = ntohl(ofm->buffer_id);
1558             fm->out_port = ntohs(ofm->out_port);
1559             fm->flags = ntohs(ofm->flags);
1560         } else if (raw == OFPRAW_NXT_FLOW_MOD) {
1561             /* Nicira extended flow_mod. */
1562             const struct nx_flow_mod *nfm;
1563             enum ofperr error;
1564
1565             /* Dissect the message. */
1566             nfm = ofpbuf_pull(&b, sizeof *nfm);
1567             error = nx_pull_match(&b, ntohs(nfm->match_len),
1568                                   &fm->match, &fm->cookie, &fm->cookie_mask);
1569             if (error) {
1570                 return error;
1571             }
1572             error = ofpacts_pull_openflow10(&b, b.size, ofpacts);
1573             if (error) {
1574                 return error;
1575             }
1576
1577             /* Translate the message. */
1578             command = ntohs(nfm->command);
1579             if ((command & 0xff) == OFPFC_ADD && fm->cookie_mask) {
1580                 /* Flow additions may only set a new cookie, not match an
1581                  * existing cookie. */
1582                 return OFPERR_NXBRC_NXM_INVALID;
1583             }
1584             fm->priority = ntohs(nfm->priority);
1585             fm->new_cookie = nfm->cookie;
1586             fm->idle_timeout = ntohs(nfm->idle_timeout);
1587             fm->hard_timeout = ntohs(nfm->hard_timeout);
1588             fm->buffer_id = ntohl(nfm->buffer_id);
1589             fm->out_port = ntohs(nfm->out_port);
1590             fm->flags = ntohs(nfm->flags);
1591         } else {
1592             NOT_REACHED();
1593         }
1594
1595         if (fm->flags & OFPFF10_EMERG) {
1596             /* We do not support the OpenFlow 1.0 emergency flow cache, which
1597              * is not required in OpenFlow 1.0.1 and removed from OpenFlow 1.1.
1598              *
1599              * OpenFlow 1.0 specifies the error code to use when idle_timeout
1600              * or hard_timeout is nonzero.  Otherwise, there is no good error
1601              * code, so just state that the flow table is full. */
1602             return (fm->hard_timeout || fm->idle_timeout
1603                     ? OFPERR_OFPFMFC_BAD_EMERG_TIMEOUT
1604                     : OFPERR_OFPFMFC_TABLE_FULL);
1605         }
1606
1607         if (protocol & OFPUTIL_P_TID) {
1608             fm->command = command & 0xff;
1609             fm->table_id = command >> 8;
1610         } else {
1611             fm->command = command;
1612             fm->table_id = 0xff;
1613         }
1614     }
1615
1616     fm->ofpacts = ofpacts->data;
1617     fm->ofpacts_len = ofpacts->size;
1618
1619     return 0;
1620 }
1621
1622 static ovs_be16
1623 ofputil_tid_command(const struct ofputil_flow_mod *fm,
1624                     enum ofputil_protocol protocol)
1625 {
1626     return htons(protocol & OFPUTIL_P_TID
1627                  ? (fm->command & 0xff) | (fm->table_id << 8)
1628                  : fm->command);
1629 }
1630
1631 /* Converts 'fm' into an OFPT_FLOW_MOD or NXT_FLOW_MOD message according to
1632  * 'protocol' and returns the message. */
1633 struct ofpbuf *
1634 ofputil_encode_flow_mod(const struct ofputil_flow_mod *fm,
1635                         enum ofputil_protocol protocol)
1636 {
1637     struct ofpbuf *msg;
1638
1639     switch (protocol) {
1640     case OFPUTIL_P_OF12_OXM:
1641     case OFPUTIL_P_OF13_OXM: {
1642         struct ofp11_flow_mod *ofm;
1643
1644         msg = ofpraw_alloc(OFPRAW_OFPT11_FLOW_MOD, 
1645                            ofputil_protocol_to_ofp_version(protocol),
1646                            NXM_TYPICAL_LEN + fm->ofpacts_len);
1647         ofm = ofpbuf_put_zeros(msg, sizeof *ofm);
1648         if (fm->command == OFPFC_ADD) {
1649             ofm->cookie = fm->new_cookie;
1650         } else {
1651             ofm->cookie = fm->cookie;
1652         }
1653         ofm->cookie_mask = fm->cookie_mask;
1654         ofm->table_id = fm->table_id;
1655         ofm->command = fm->command;
1656         ofm->idle_timeout = htons(fm->idle_timeout);
1657         ofm->hard_timeout = htons(fm->hard_timeout);
1658         ofm->priority = htons(fm->priority);
1659         ofm->buffer_id = htonl(fm->buffer_id);
1660         ofm->out_port = ofputil_port_to_ofp11(fm->out_port);
1661         ofm->out_group = htonl(OFPG11_ANY);
1662         ofm->flags = htons(fm->flags);
1663         oxm_put_match(msg, &fm->match);
1664         ofpacts_put_openflow11_instructions(fm->ofpacts, fm->ofpacts_len, msg);
1665         break;
1666     }
1667
1668     case OFPUTIL_P_OF10_STD:
1669     case OFPUTIL_P_OF10_STD_TID: {
1670         struct ofp10_flow_mod *ofm;
1671
1672         msg = ofpraw_alloc(OFPRAW_OFPT10_FLOW_MOD, OFP10_VERSION,
1673                            fm->ofpacts_len);
1674         ofm = ofpbuf_put_zeros(msg, sizeof *ofm);
1675         ofputil_match_to_ofp10_match(&fm->match, &ofm->match);
1676         ofm->cookie = fm->new_cookie;
1677         ofm->command = ofputil_tid_command(fm, protocol);
1678         ofm->idle_timeout = htons(fm->idle_timeout);
1679         ofm->hard_timeout = htons(fm->hard_timeout);
1680         ofm->priority = htons(fm->priority);
1681         ofm->buffer_id = htonl(fm->buffer_id);
1682         ofm->out_port = htons(fm->out_port);
1683         ofm->flags = htons(fm->flags);
1684         ofpacts_put_openflow10(fm->ofpacts, fm->ofpacts_len, msg);
1685         break;
1686     }
1687
1688     case OFPUTIL_P_OF10_NXM:
1689     case OFPUTIL_P_OF10_NXM_TID: {
1690         struct nx_flow_mod *nfm;
1691         int match_len;
1692
1693         msg = ofpraw_alloc(OFPRAW_NXT_FLOW_MOD, OFP10_VERSION,
1694                            NXM_TYPICAL_LEN + fm->ofpacts_len);
1695         nfm = ofpbuf_put_zeros(msg, sizeof *nfm);
1696         nfm->command = ofputil_tid_command(fm, protocol);
1697         nfm->cookie = fm->new_cookie;
1698         match_len = nx_put_match(msg, &fm->match, fm->cookie, fm->cookie_mask);
1699         nfm = msg->l3;
1700         nfm->idle_timeout = htons(fm->idle_timeout);
1701         nfm->hard_timeout = htons(fm->hard_timeout);
1702         nfm->priority = htons(fm->priority);
1703         nfm->buffer_id = htonl(fm->buffer_id);
1704         nfm->out_port = htons(fm->out_port);
1705         nfm->flags = htons(fm->flags);
1706         nfm->match_len = htons(match_len);
1707         ofpacts_put_openflow10(fm->ofpacts, fm->ofpacts_len, msg);
1708         break;
1709     }
1710
1711     default:
1712         NOT_REACHED();
1713     }
1714
1715     ofpmsg_update_length(msg);
1716     return msg;
1717 }
1718
1719 /* Returns a bitmask with a 1-bit for each protocol that could be used to
1720  * send all of the 'n_fm's flow table modification requests in 'fms', and a
1721  * 0-bit for each protocol that is inadequate.
1722  *
1723  * (The return value will have at least one 1-bit.) */
1724 enum ofputil_protocol
1725 ofputil_flow_mod_usable_protocols(const struct ofputil_flow_mod *fms,
1726                                   size_t n_fms)
1727 {
1728     enum ofputil_protocol usable_protocols;
1729     size_t i;
1730
1731     usable_protocols = OFPUTIL_P_ANY;
1732     for (i = 0; i < n_fms; i++) {
1733         const struct ofputil_flow_mod *fm = &fms[i];
1734
1735         usable_protocols &= ofputil_usable_protocols(&fm->match);
1736         if (fm->table_id != 0xff) {
1737             usable_protocols &= OFPUTIL_P_TID;
1738         }
1739
1740         /* Matching of the cookie is only supported through NXM or OF1.1+. */
1741         if (fm->cookie_mask != htonll(0)) {
1742             usable_protocols &= OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1743                 | OFPUTIL_P_OF13_OXM;
1744         }
1745     }
1746
1747     return usable_protocols;
1748 }
1749
1750 static enum ofperr
1751 ofputil_decode_ofpst10_flow_request(struct ofputil_flow_stats_request *fsr,
1752                                     const struct ofp10_flow_stats_request *ofsr,
1753                                     bool aggregate)
1754 {
1755     fsr->aggregate = aggregate;
1756     ofputil_match_from_ofp10_match(&ofsr->match, &fsr->match);
1757     fsr->out_port = ntohs(ofsr->out_port);
1758     fsr->table_id = ofsr->table_id;
1759     fsr->cookie = fsr->cookie_mask = htonll(0);
1760
1761     return 0;
1762 }
1763
1764 static enum ofperr
1765 ofputil_decode_ofpst11_flow_request(struct ofputil_flow_stats_request *fsr,
1766                                     struct ofpbuf *b, bool aggregate)
1767 {
1768     const struct ofp11_flow_stats_request *ofsr;
1769     enum ofperr error;
1770
1771     ofsr = ofpbuf_pull(b, sizeof *ofsr);
1772     fsr->aggregate = aggregate;
1773     fsr->table_id = ofsr->table_id;
1774     error = ofputil_port_from_ofp11(ofsr->out_port, &fsr->out_port);
1775     if (error) {
1776         return error;
1777     }
1778     if (ofsr->out_group != htonl(OFPG11_ANY)) {
1779         return OFPERR_OFPFMFC_UNKNOWN;
1780     }
1781     fsr->cookie = ofsr->cookie;
1782     fsr->cookie_mask = ofsr->cookie_mask;
1783     error = ofputil_pull_ofp11_match(b, &fsr->match, NULL);
1784     if (error) {
1785         return error;
1786     }
1787
1788     return 0;
1789 }
1790
1791 static enum ofperr
1792 ofputil_decode_nxst_flow_request(struct ofputil_flow_stats_request *fsr,
1793                                  struct ofpbuf *b, bool aggregate)
1794 {
1795     const struct nx_flow_stats_request *nfsr;
1796     enum ofperr error;
1797
1798     nfsr = ofpbuf_pull(b, sizeof *nfsr);
1799     error = nx_pull_match(b, ntohs(nfsr->match_len), &fsr->match,
1800                           &fsr->cookie, &fsr->cookie_mask);
1801     if (error) {
1802         return error;
1803     }
1804     if (b->size) {
1805         return OFPERR_OFPBRC_BAD_LEN;
1806     }
1807
1808     fsr->aggregate = aggregate;
1809     fsr->out_port = ntohs(nfsr->out_port);
1810     fsr->table_id = nfsr->table_id;
1811
1812     return 0;
1813 }
1814
1815 /* Converts an OFPST_FLOW, OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE
1816  * request 'oh', into an abstract flow_stats_request in 'fsr'.  Returns 0 if
1817  * successful, otherwise an OpenFlow error code. */
1818 enum ofperr
1819 ofputil_decode_flow_stats_request(struct ofputil_flow_stats_request *fsr,
1820                                   const struct ofp_header *oh)
1821 {
1822     enum ofpraw raw;
1823     struct ofpbuf b;
1824
1825     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1826     raw = ofpraw_pull_assert(&b);
1827     switch ((int) raw) {
1828     case OFPRAW_OFPST10_FLOW_REQUEST:
1829         return ofputil_decode_ofpst10_flow_request(fsr, b.data, false);
1830
1831     case OFPRAW_OFPST10_AGGREGATE_REQUEST:
1832         return ofputil_decode_ofpst10_flow_request(fsr, b.data, true);
1833
1834     case OFPRAW_OFPST11_FLOW_REQUEST:
1835         return ofputil_decode_ofpst11_flow_request(fsr, &b, false);
1836
1837     case OFPRAW_OFPST11_AGGREGATE_REQUEST:
1838         return ofputil_decode_ofpst11_flow_request(fsr, &b, true);
1839
1840     case OFPRAW_NXST_FLOW_REQUEST:
1841         return ofputil_decode_nxst_flow_request(fsr, &b, false);
1842
1843     case OFPRAW_NXST_AGGREGATE_REQUEST:
1844         return ofputil_decode_nxst_flow_request(fsr, &b, true);
1845
1846     default:
1847         /* Hey, the caller lied. */
1848         NOT_REACHED();
1849     }
1850 }
1851
1852 /* Converts abstract flow_stats_request 'fsr' into an OFPST_FLOW,
1853  * OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE request 'oh' according to
1854  * 'protocol', and returns the message. */
1855 struct ofpbuf *
1856 ofputil_encode_flow_stats_request(const struct ofputil_flow_stats_request *fsr,
1857                                   enum ofputil_protocol protocol)
1858 {
1859     struct ofpbuf *msg;
1860     enum ofpraw raw;
1861
1862     switch (protocol) {
1863     case OFPUTIL_P_OF12_OXM:
1864     case OFPUTIL_P_OF13_OXM: {
1865         struct ofp11_flow_stats_request *ofsr;
1866
1867         raw = (fsr->aggregate
1868                ? OFPRAW_OFPST11_AGGREGATE_REQUEST
1869                : OFPRAW_OFPST11_FLOW_REQUEST);
1870         msg = ofpraw_alloc(raw, ofputil_protocol_to_ofp_version(protocol),
1871                            NXM_TYPICAL_LEN);
1872         ofsr = ofpbuf_put_zeros(msg, sizeof *ofsr);
1873         ofsr->table_id = fsr->table_id;
1874         ofsr->out_port = ofputil_port_to_ofp11(fsr->out_port);
1875         ofsr->out_group = htonl(OFPG11_ANY);
1876         ofsr->cookie = fsr->cookie;
1877         ofsr->cookie_mask = fsr->cookie_mask;
1878         oxm_put_match(msg, &fsr->match);
1879         break;
1880     }
1881
1882     case OFPUTIL_P_OF10_STD:
1883     case OFPUTIL_P_OF10_STD_TID: {
1884         struct ofp10_flow_stats_request *ofsr;
1885
1886         raw = (fsr->aggregate
1887                ? OFPRAW_OFPST10_AGGREGATE_REQUEST
1888                : OFPRAW_OFPST10_FLOW_REQUEST);
1889         msg = ofpraw_alloc(raw, OFP10_VERSION, 0);
1890         ofsr = ofpbuf_put_zeros(msg, sizeof *ofsr);
1891         ofputil_match_to_ofp10_match(&fsr->match, &ofsr->match);
1892         ofsr->table_id = fsr->table_id;
1893         ofsr->out_port = htons(fsr->out_port);
1894         break;
1895     }
1896
1897     case OFPUTIL_P_OF10_NXM:
1898     case OFPUTIL_P_OF10_NXM_TID: {
1899         struct nx_flow_stats_request *nfsr;
1900         int match_len;
1901
1902         raw = (fsr->aggregate
1903                ? OFPRAW_NXST_AGGREGATE_REQUEST
1904                : OFPRAW_NXST_FLOW_REQUEST);
1905         msg = ofpraw_alloc(raw, OFP10_VERSION, NXM_TYPICAL_LEN);
1906         ofpbuf_put_zeros(msg, sizeof *nfsr);
1907         match_len = nx_put_match(msg, &fsr->match,
1908                                  fsr->cookie, fsr->cookie_mask);
1909
1910         nfsr = msg->l3;
1911         nfsr->out_port = htons(fsr->out_port);
1912         nfsr->match_len = htons(match_len);
1913         nfsr->table_id = fsr->table_id;
1914         break;
1915     }
1916
1917     default:
1918         NOT_REACHED();
1919     }
1920
1921     return msg;
1922 }
1923
1924 /* Returns a bitmask with a 1-bit for each protocol that could be used to
1925  * accurately encode 'fsr', and a 0-bit for each protocol that is inadequate.
1926  *
1927  * (The return value will have at least one 1-bit.) */
1928 enum ofputil_protocol
1929 ofputil_flow_stats_request_usable_protocols(
1930     const struct ofputil_flow_stats_request *fsr)
1931 {
1932     enum ofputil_protocol usable_protocols;
1933
1934     usable_protocols = ofputil_usable_protocols(&fsr->match);
1935     if (fsr->cookie_mask != htonll(0)) {
1936         usable_protocols &= OFPUTIL_P_OF10_NXM_ANY | OFPUTIL_P_OF12_OXM
1937             | OFPUTIL_P_OF13_OXM;
1938     }
1939     return usable_protocols;
1940 }
1941
1942 /* Converts an OFPST_FLOW or NXST_FLOW reply in 'msg' into an abstract
1943  * ofputil_flow_stats in 'fs'.
1944  *
1945  * Multiple OFPST_FLOW or NXST_FLOW replies can be packed into a single
1946  * OpenFlow message.  Calling this function multiple times for a single 'msg'
1947  * iterates through the replies.  The caller must initially leave 'msg''s layer
1948  * pointers null and not modify them between calls.
1949  *
1950  * Most switches don't send the values needed to populate fs->idle_age and
1951  * fs->hard_age, so those members will usually be set to 0.  If the switch from
1952  * which 'msg' originated is known to implement NXT_FLOW_AGE, then pass
1953  * 'flow_age_extension' as true so that the contents of 'msg' determine the
1954  * 'idle_age' and 'hard_age' members in 'fs'.
1955  *
1956  * Uses 'ofpacts' to store the abstract OFPACT_* version of the flow stats
1957  * reply's actions.  The caller must initialize 'ofpacts' and retains ownership
1958  * of it.  'fs->ofpacts' will point into the 'ofpacts' buffer.
1959  *
1960  * Returns 0 if successful, EOF if no replies were left in this 'msg',
1961  * otherwise a positive errno value. */
1962 int
1963 ofputil_decode_flow_stats_reply(struct ofputil_flow_stats *fs,
1964                                 struct ofpbuf *msg,
1965                                 bool flow_age_extension,
1966                                 struct ofpbuf *ofpacts)
1967 {
1968     enum ofperr error;
1969     enum ofpraw raw;
1970
1971     error = (msg->l2
1972              ? ofpraw_decode(&raw, msg->l2)
1973              : ofpraw_pull(&raw, msg));
1974     if (error) {
1975         return error;
1976     }
1977
1978     if (!msg->size) {
1979         return EOF;
1980     } else if (raw == OFPRAW_OFPST11_FLOW_REPLY
1981                || raw == OFPRAW_OFPST13_FLOW_REPLY) {
1982         const struct ofp11_flow_stats *ofs;
1983         size_t length;
1984         uint16_t padded_match_len;
1985
1986         ofs = ofpbuf_try_pull(msg, sizeof *ofs);
1987         if (!ofs) {
1988             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply has %zu leftover "
1989                          "bytes at end", msg->size);
1990             return EINVAL;
1991         }
1992
1993         length = ntohs(ofs->length);
1994         if (length < sizeof *ofs) {
1995             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply claims invalid "
1996                          "length %zu", length);
1997             return EINVAL;
1998         }
1999
2000         if (ofputil_pull_ofp11_match(msg, &fs->match, &padded_match_len)) {
2001             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply bad match");
2002             return EINVAL;
2003         }
2004
2005         if (ofpacts_pull_openflow11_instructions(msg, length - sizeof *ofs -
2006                                                  padded_match_len, ofpacts)) {
2007             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply bad instructions");
2008             return EINVAL;
2009         }
2010
2011         fs->priority = ntohs(ofs->priority);
2012         fs->table_id = ofs->table_id;
2013         fs->duration_sec = ntohl(ofs->duration_sec);
2014         fs->duration_nsec = ntohl(ofs->duration_nsec);
2015         fs->idle_timeout = ntohs(ofs->idle_timeout);
2016         fs->hard_timeout = ntohs(ofs->hard_timeout);
2017         fs->flags = (raw == OFPRAW_OFPST13_FLOW_REPLY) ? ntohs(ofs->flags) : 0;
2018         fs->idle_age = -1;
2019         fs->hard_age = -1;
2020         fs->cookie = ofs->cookie;
2021         fs->packet_count = ntohll(ofs->packet_count);
2022         fs->byte_count = ntohll(ofs->byte_count);
2023     } else if (raw == OFPRAW_OFPST10_FLOW_REPLY) {
2024         const struct ofp10_flow_stats *ofs;
2025         size_t length;
2026
2027         ofs = ofpbuf_try_pull(msg, sizeof *ofs);
2028         if (!ofs) {
2029             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply has %zu leftover "
2030                          "bytes at end", msg->size);
2031             return EINVAL;
2032         }
2033
2034         length = ntohs(ofs->length);
2035         if (length < sizeof *ofs) {
2036             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply claims invalid "
2037                          "length %zu", length);
2038             return EINVAL;
2039         }
2040
2041         if (ofpacts_pull_openflow10(msg, length - sizeof *ofs, ofpacts)) {
2042             return EINVAL;
2043         }
2044
2045         fs->cookie = get_32aligned_be64(&ofs->cookie);
2046         ofputil_match_from_ofp10_match(&ofs->match, &fs->match);
2047         fs->priority = ntohs(ofs->priority);
2048         fs->table_id = ofs->table_id;
2049         fs->duration_sec = ntohl(ofs->duration_sec);
2050         fs->duration_nsec = ntohl(ofs->duration_nsec);
2051         fs->idle_timeout = ntohs(ofs->idle_timeout);
2052         fs->hard_timeout = ntohs(ofs->hard_timeout);
2053         fs->idle_age = -1;
2054         fs->hard_age = -1;
2055         fs->packet_count = ntohll(get_32aligned_be64(&ofs->packet_count));
2056         fs->byte_count = ntohll(get_32aligned_be64(&ofs->byte_count));
2057         fs->flags = 0;
2058     } else if (raw == OFPRAW_NXST_FLOW_REPLY) {
2059         const struct nx_flow_stats *nfs;
2060         size_t match_len, actions_len, length;
2061
2062         nfs = ofpbuf_try_pull(msg, sizeof *nfs);
2063         if (!nfs) {
2064             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply has %zu leftover "
2065                          "bytes at end", msg->size);
2066             return EINVAL;
2067         }
2068
2069         length = ntohs(nfs->length);
2070         match_len = ntohs(nfs->match_len);
2071         if (length < sizeof *nfs + ROUND_UP(match_len, 8)) {
2072             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply with match_len=%zu "
2073                          "claims invalid length %zu", match_len, length);
2074             return EINVAL;
2075         }
2076         if (nx_pull_match(msg, match_len, &fs->match, NULL, NULL)) {
2077             return EINVAL;
2078         }
2079
2080         actions_len = length - sizeof *nfs - ROUND_UP(match_len, 8);
2081         if (ofpacts_pull_openflow10(msg, actions_len, ofpacts)) {
2082             return EINVAL;
2083         }
2084
2085         fs->cookie = nfs->cookie;
2086         fs->table_id = nfs->table_id;
2087         fs->duration_sec = ntohl(nfs->duration_sec);
2088         fs->duration_nsec = ntohl(nfs->duration_nsec);
2089         fs->priority = ntohs(nfs->priority);
2090         fs->idle_timeout = ntohs(nfs->idle_timeout);
2091         fs->hard_timeout = ntohs(nfs->hard_timeout);
2092         fs->idle_age = -1;
2093         fs->hard_age = -1;
2094         if (flow_age_extension) {
2095             if (nfs->idle_age) {
2096                 fs->idle_age = ntohs(nfs->idle_age) - 1;
2097             }
2098             if (nfs->hard_age) {
2099                 fs->hard_age = ntohs(nfs->hard_age) - 1;
2100             }
2101         }
2102         fs->packet_count = ntohll(nfs->packet_count);
2103         fs->byte_count = ntohll(nfs->byte_count);
2104         fs->flags = 0;
2105     } else {
2106         NOT_REACHED();
2107     }
2108
2109     fs->ofpacts = ofpacts->data;
2110     fs->ofpacts_len = ofpacts->size;
2111
2112     return 0;
2113 }
2114
2115 /* Returns 'count' unchanged except that UINT64_MAX becomes 0.
2116  *
2117  * We use this in situations where OVS internally uses UINT64_MAX to mean
2118  * "value unknown" but OpenFlow 1.0 does not define any unknown value. */
2119 static uint64_t
2120 unknown_to_zero(uint64_t count)
2121 {
2122     return count != UINT64_MAX ? count : 0;
2123 }
2124
2125 /* Appends an OFPST_FLOW or NXST_FLOW reply that contains the data in 'fs' to
2126  * those already present in the list of ofpbufs in 'replies'.  'replies' should
2127  * have been initialized with ofputil_start_stats_reply(). */
2128 void
2129 ofputil_append_flow_stats_reply(const struct ofputil_flow_stats *fs,
2130                                 struct list *replies)
2131 {
2132     struct ofpbuf *reply = ofpbuf_from_list(list_back(replies));
2133     size_t start_ofs = reply->size;
2134     enum ofpraw raw;
2135
2136     ofpraw_decode_partial(&raw, reply->data, reply->size);
2137     if (raw == OFPRAW_OFPST11_FLOW_REPLY || raw == OFPRAW_OFPST13_FLOW_REPLY) {
2138         struct ofp11_flow_stats *ofs;
2139
2140         ofpbuf_put_uninit(reply, sizeof *ofs);
2141         oxm_put_match(reply, &fs->match);
2142         ofpacts_put_openflow11_instructions(fs->ofpacts, fs->ofpacts_len,
2143                                             reply);
2144
2145         ofs = ofpbuf_at_assert(reply, start_ofs, sizeof *ofs);
2146         ofs->length = htons(reply->size - start_ofs);
2147         ofs->table_id = fs->table_id;
2148         ofs->pad = 0;
2149         ofs->duration_sec = htonl(fs->duration_sec);
2150         ofs->duration_nsec = htonl(fs->duration_nsec);
2151         ofs->priority = htons(fs->priority);
2152         ofs->idle_timeout = htons(fs->idle_timeout);
2153         ofs->hard_timeout = htons(fs->hard_timeout);
2154         ofs->flags = (raw == OFPRAW_OFPST13_FLOW_REPLY) ? htons(fs->flags) : 0;
2155         memset(ofs->pad2, 0, sizeof ofs->pad2);
2156         ofs->cookie = fs->cookie;
2157         ofs->packet_count = htonll(unknown_to_zero(fs->packet_count));
2158         ofs->byte_count = htonll(unknown_to_zero(fs->byte_count));
2159     } else if (raw == OFPRAW_OFPST10_FLOW_REPLY) {
2160         struct ofp10_flow_stats *ofs;
2161
2162         ofpbuf_put_uninit(reply, sizeof *ofs);
2163         ofpacts_put_openflow10(fs->ofpacts, fs->ofpacts_len, reply);
2164
2165         ofs = ofpbuf_at_assert(reply, start_ofs, sizeof *ofs);
2166         ofs->length = htons(reply->size - start_ofs);
2167         ofs->table_id = fs->table_id;
2168         ofs->pad = 0;
2169         ofputil_match_to_ofp10_match(&fs->match, &ofs->match);
2170         ofs->duration_sec = htonl(fs->duration_sec);
2171         ofs->duration_nsec = htonl(fs->duration_nsec);
2172         ofs->priority = htons(fs->priority);
2173         ofs->idle_timeout = htons(fs->idle_timeout);
2174         ofs->hard_timeout = htons(fs->hard_timeout);
2175         memset(ofs->pad2, 0, sizeof ofs->pad2);
2176         put_32aligned_be64(&ofs->cookie, fs->cookie);
2177         put_32aligned_be64(&ofs->packet_count,
2178                            htonll(unknown_to_zero(fs->packet_count)));
2179         put_32aligned_be64(&ofs->byte_count,
2180                            htonll(unknown_to_zero(fs->byte_count)));
2181     } else if (raw == OFPRAW_NXST_FLOW_REPLY) {
2182         struct nx_flow_stats *nfs;
2183         int match_len;
2184
2185         ofpbuf_put_uninit(reply, sizeof *nfs);
2186         match_len = nx_put_match(reply, &fs->match, 0, 0);
2187         ofpacts_put_openflow10(fs->ofpacts, fs->ofpacts_len, reply);
2188
2189         nfs = ofpbuf_at_assert(reply, start_ofs, sizeof *nfs);
2190         nfs->length = htons(reply->size - start_ofs);
2191         nfs->table_id = fs->table_id;
2192         nfs->pad = 0;
2193         nfs->duration_sec = htonl(fs->duration_sec);
2194         nfs->duration_nsec = htonl(fs->duration_nsec);
2195         nfs->priority = htons(fs->priority);
2196         nfs->idle_timeout = htons(fs->idle_timeout);
2197         nfs->hard_timeout = htons(fs->hard_timeout);
2198         nfs->idle_age = htons(fs->idle_age < 0 ? 0
2199                               : fs->idle_age < UINT16_MAX ? fs->idle_age + 1
2200                               : UINT16_MAX);
2201         nfs->hard_age = htons(fs->hard_age < 0 ? 0
2202                               : fs->hard_age < UINT16_MAX ? fs->hard_age + 1
2203                               : UINT16_MAX);
2204         nfs->match_len = htons(match_len);
2205         nfs->cookie = fs->cookie;
2206         nfs->packet_count = htonll(fs->packet_count);
2207         nfs->byte_count = htonll(fs->byte_count);
2208     } else {
2209         NOT_REACHED();
2210     }
2211
2212     ofpmp_postappend(replies, start_ofs);
2213 }
2214
2215 /* Converts abstract ofputil_aggregate_stats 'stats' into an OFPST_AGGREGATE or
2216  * NXST_AGGREGATE reply matching 'request', and returns the message. */
2217 struct ofpbuf *
2218 ofputil_encode_aggregate_stats_reply(
2219     const struct ofputil_aggregate_stats *stats,
2220     const struct ofp_header *request)
2221 {
2222     struct ofp_aggregate_stats_reply *asr;
2223     uint64_t packet_count;
2224     uint64_t byte_count;
2225     struct ofpbuf *msg;
2226     enum ofpraw raw;
2227
2228     ofpraw_decode(&raw, request);
2229     if (raw == OFPRAW_OFPST10_AGGREGATE_REQUEST) {
2230         packet_count = unknown_to_zero(stats->packet_count);
2231         byte_count = unknown_to_zero(stats->byte_count);
2232     } else {
2233         packet_count = stats->packet_count;
2234         byte_count = stats->byte_count;
2235     }
2236
2237     msg = ofpraw_alloc_stats_reply(request, 0);
2238     asr = ofpbuf_put_zeros(msg, sizeof *asr);
2239     put_32aligned_be64(&asr->packet_count, htonll(packet_count));
2240     put_32aligned_be64(&asr->byte_count, htonll(byte_count));
2241     asr->flow_count = htonl(stats->flow_count);
2242
2243     return msg;
2244 }
2245
2246 enum ofperr
2247 ofputil_decode_aggregate_stats_reply(struct ofputil_aggregate_stats *stats,
2248                                      const struct ofp_header *reply)
2249 {
2250     struct ofp_aggregate_stats_reply *asr;
2251     struct ofpbuf msg;
2252
2253     ofpbuf_use_const(&msg, reply, ntohs(reply->length));
2254     ofpraw_pull_assert(&msg);
2255
2256     asr = msg.l3;
2257     stats->packet_count = ntohll(get_32aligned_be64(&asr->packet_count));
2258     stats->byte_count = ntohll(get_32aligned_be64(&asr->byte_count));
2259     stats->flow_count = ntohl(asr->flow_count);
2260
2261     return 0;
2262 }
2263
2264 /* Converts an OFPT_FLOW_REMOVED or NXT_FLOW_REMOVED message 'oh' into an
2265  * abstract ofputil_flow_removed in 'fr'.  Returns 0 if successful, otherwise
2266  * an OpenFlow error code. */
2267 enum ofperr
2268 ofputil_decode_flow_removed(struct ofputil_flow_removed *fr,
2269                             const struct ofp_header *oh)
2270 {
2271     enum ofpraw raw;
2272     struct ofpbuf b;
2273
2274     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2275     raw = ofpraw_pull_assert(&b);
2276     if (raw == OFPRAW_OFPT11_FLOW_REMOVED) {
2277         const struct ofp12_flow_removed *ofr;
2278         enum ofperr error;
2279
2280         ofr = ofpbuf_pull(&b, sizeof *ofr);
2281
2282         error = ofputil_pull_ofp11_match(&b, &fr->match, NULL);
2283         if (error) {
2284             return error;
2285         }
2286
2287         fr->priority = ntohs(ofr->priority);
2288         fr->cookie = ofr->cookie;
2289         fr->reason = ofr->reason;
2290         fr->table_id = ofr->table_id;
2291         fr->duration_sec = ntohl(ofr->duration_sec);
2292         fr->duration_nsec = ntohl(ofr->duration_nsec);
2293         fr->idle_timeout = ntohs(ofr->idle_timeout);
2294         fr->hard_timeout = ntohs(ofr->hard_timeout);
2295         fr->packet_count = ntohll(ofr->packet_count);
2296         fr->byte_count = ntohll(ofr->byte_count);
2297     } else if (raw == OFPRAW_OFPT10_FLOW_REMOVED) {
2298         const struct ofp10_flow_removed *ofr;
2299
2300         ofr = ofpbuf_pull(&b, sizeof *ofr);
2301
2302         ofputil_match_from_ofp10_match(&ofr->match, &fr->match);
2303         fr->priority = ntohs(ofr->priority);
2304         fr->cookie = ofr->cookie;
2305         fr->reason = ofr->reason;
2306         fr->table_id = 255;
2307         fr->duration_sec = ntohl(ofr->duration_sec);
2308         fr->duration_nsec = ntohl(ofr->duration_nsec);
2309         fr->idle_timeout = ntohs(ofr->idle_timeout);
2310         fr->hard_timeout = 0;
2311         fr->packet_count = ntohll(ofr->packet_count);
2312         fr->byte_count = ntohll(ofr->byte_count);
2313     } else if (raw == OFPRAW_NXT_FLOW_REMOVED) {
2314         struct nx_flow_removed *nfr;
2315         enum ofperr error;
2316
2317         nfr = ofpbuf_pull(&b, sizeof *nfr);
2318         error = nx_pull_match(&b, ntohs(nfr->match_len), &fr->match,
2319                               NULL, NULL);
2320         if (error) {
2321             return error;
2322         }
2323         if (b.size) {
2324             return OFPERR_OFPBRC_BAD_LEN;
2325         }
2326
2327         fr->priority = ntohs(nfr->priority);
2328         fr->cookie = nfr->cookie;
2329         fr->reason = nfr->reason;
2330         fr->table_id = 255;
2331         fr->duration_sec = ntohl(nfr->duration_sec);
2332         fr->duration_nsec = ntohl(nfr->duration_nsec);
2333         fr->idle_timeout = ntohs(nfr->idle_timeout);
2334         fr->hard_timeout = 0;
2335         fr->packet_count = ntohll(nfr->packet_count);
2336         fr->byte_count = ntohll(nfr->byte_count);
2337     } else {
2338         NOT_REACHED();
2339     }
2340
2341     return 0;
2342 }
2343
2344 /* Converts abstract ofputil_flow_removed 'fr' into an OFPT_FLOW_REMOVED or
2345  * NXT_FLOW_REMOVED message 'oh' according to 'protocol', and returns the
2346  * message. */
2347 struct ofpbuf *
2348 ofputil_encode_flow_removed(const struct ofputil_flow_removed *fr,
2349                             enum ofputil_protocol protocol)
2350 {
2351     struct ofpbuf *msg;
2352
2353     switch (protocol) {
2354     case OFPUTIL_P_OF12_OXM:
2355     case OFPUTIL_P_OF13_OXM: {
2356         struct ofp12_flow_removed *ofr;
2357
2358         msg = ofpraw_alloc_xid(OFPRAW_OFPT11_FLOW_REMOVED,
2359                                ofputil_protocol_to_ofp_version(protocol),
2360                                htonl(0), NXM_TYPICAL_LEN);
2361         ofr = ofpbuf_put_zeros(msg, sizeof *ofr);
2362         ofr->cookie = fr->cookie;
2363         ofr->priority = htons(fr->priority);
2364         ofr->reason = fr->reason;
2365         ofr->table_id = fr->table_id;
2366         ofr->duration_sec = htonl(fr->duration_sec);
2367         ofr->duration_nsec = htonl(fr->duration_nsec);
2368         ofr->idle_timeout = htons(fr->idle_timeout);
2369         ofr->hard_timeout = htons(fr->hard_timeout);
2370         ofr->packet_count = htonll(fr->packet_count);
2371         ofr->byte_count = htonll(fr->byte_count);
2372         oxm_put_match(msg, &fr->match);
2373         break;
2374     }
2375
2376     case OFPUTIL_P_OF10_STD:
2377     case OFPUTIL_P_OF10_STD_TID: {
2378         struct ofp10_flow_removed *ofr;
2379
2380         msg = ofpraw_alloc_xid(OFPRAW_OFPT10_FLOW_REMOVED, OFP10_VERSION,
2381                                htonl(0), 0);
2382         ofr = ofpbuf_put_zeros(msg, sizeof *ofr);
2383         ofputil_match_to_ofp10_match(&fr->match, &ofr->match);
2384         ofr->cookie = fr->cookie;
2385         ofr->priority = htons(fr->priority);
2386         ofr->reason = fr->reason;
2387         ofr->duration_sec = htonl(fr->duration_sec);
2388         ofr->duration_nsec = htonl(fr->duration_nsec);
2389         ofr->idle_timeout = htons(fr->idle_timeout);
2390         ofr->packet_count = htonll(unknown_to_zero(fr->packet_count));
2391         ofr->byte_count = htonll(unknown_to_zero(fr->byte_count));
2392         break;
2393     }
2394
2395     case OFPUTIL_P_OF10_NXM:
2396     case OFPUTIL_P_OF10_NXM_TID: {
2397         struct nx_flow_removed *nfr;
2398         int match_len;
2399
2400         msg = ofpraw_alloc_xid(OFPRAW_NXT_FLOW_REMOVED, OFP10_VERSION,
2401                                htonl(0), NXM_TYPICAL_LEN);
2402         nfr = ofpbuf_put_zeros(msg, sizeof *nfr);
2403         match_len = nx_put_match(msg, &fr->match, 0, 0);
2404
2405         nfr = msg->l3;
2406         nfr->cookie = fr->cookie;
2407         nfr->priority = htons(fr->priority);
2408         nfr->reason = fr->reason;
2409         nfr->duration_sec = htonl(fr->duration_sec);
2410         nfr->duration_nsec = htonl(fr->duration_nsec);
2411         nfr->idle_timeout = htons(fr->idle_timeout);
2412         nfr->match_len = htons(match_len);
2413         nfr->packet_count = htonll(fr->packet_count);
2414         nfr->byte_count = htonll(fr->byte_count);
2415         break;
2416     }
2417
2418     default:
2419         NOT_REACHED();
2420     }
2421
2422     return msg;
2423 }
2424
2425 static void
2426 ofputil_decode_packet_in_finish(struct ofputil_packet_in *pin,
2427                                 struct match *match, struct ofpbuf *b)
2428 {
2429     pin->packet = b->data;
2430     pin->packet_len = b->size;
2431
2432     pin->fmd.in_port = match->flow.in_port;
2433     pin->fmd.tun_id = match->flow.tunnel.tun_id;
2434     pin->fmd.metadata = match->flow.metadata;
2435     memcpy(pin->fmd.regs, match->flow.regs, sizeof pin->fmd.regs);
2436 }
2437
2438 enum ofperr
2439 ofputil_decode_packet_in(struct ofputil_packet_in *pin,
2440                          const struct ofp_header *oh)
2441 {
2442     enum ofpraw raw;
2443     struct ofpbuf b;
2444
2445     memset(pin, 0, sizeof *pin);
2446
2447     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2448     raw = ofpraw_pull_assert(&b);
2449     if (raw == OFPRAW_OFPT13_PACKET_IN || raw == OFPRAW_OFPT12_PACKET_IN) {
2450         const struct ofp13_packet_in *opi;
2451         struct match match;
2452         int error;
2453         size_t packet_in_size;
2454
2455         if (raw == OFPRAW_OFPT12_PACKET_IN) {
2456             packet_in_size = sizeof (struct ofp12_packet_in);
2457         } else {
2458             packet_in_size = sizeof (struct ofp13_packet_in);
2459         }
2460
2461         opi = ofpbuf_pull(&b, packet_in_size);
2462         error = oxm_pull_match_loose(&b, &match);
2463         if (error) {
2464             return error;
2465         }
2466
2467         if (!ofpbuf_try_pull(&b, 2)) {
2468             return OFPERR_OFPBRC_BAD_LEN;
2469         }
2470
2471         pin->reason = opi->pi.reason;
2472         pin->table_id = opi->pi.table_id;
2473         pin->buffer_id = ntohl(opi->pi.buffer_id);
2474         pin->total_len = ntohs(opi->pi.total_len);
2475
2476         if (raw == OFPRAW_OFPT13_PACKET_IN) {
2477             pin->cookie = opi->cookie;
2478         }
2479
2480         ofputil_decode_packet_in_finish(pin, &match, &b);
2481     } else if (raw == OFPRAW_OFPT10_PACKET_IN) {
2482         const struct ofp10_packet_in *opi;
2483
2484         opi = ofpbuf_pull(&b, offsetof(struct ofp10_packet_in, data));
2485
2486         pin->packet = opi->data;
2487         pin->packet_len = b.size;
2488
2489         pin->fmd.in_port = ntohs(opi->in_port);
2490         pin->reason = opi->reason;
2491         pin->buffer_id = ntohl(opi->buffer_id);
2492         pin->total_len = ntohs(opi->total_len);
2493     } else if (raw == OFPRAW_NXT_PACKET_IN) {
2494         const struct nx_packet_in *npi;
2495         struct match match;
2496         int error;
2497
2498         npi = ofpbuf_pull(&b, sizeof *npi);
2499         error = nx_pull_match_loose(&b, ntohs(npi->match_len), &match, NULL,
2500                                     NULL);
2501         if (error) {
2502             return error;
2503         }
2504
2505         if (!ofpbuf_try_pull(&b, 2)) {
2506             return OFPERR_OFPBRC_BAD_LEN;
2507         }
2508
2509         pin->reason = npi->reason;
2510         pin->table_id = npi->table_id;
2511         pin->cookie = npi->cookie;
2512
2513         pin->buffer_id = ntohl(npi->buffer_id);
2514         pin->total_len = ntohs(npi->total_len);
2515
2516         ofputil_decode_packet_in_finish(pin, &match, &b);
2517     } else {
2518         NOT_REACHED();
2519     }
2520
2521     return 0;
2522 }
2523
2524 static void
2525 ofputil_packet_in_to_match(const struct ofputil_packet_in *pin,
2526                            struct match *match)
2527 {
2528     int i;
2529
2530     match_init_catchall(match);
2531     if (pin->fmd.tun_id != htonll(0)) {
2532         match_set_tun_id(match, pin->fmd.tun_id);
2533     }
2534     if (pin->fmd.metadata != htonll(0)) {
2535         match_set_metadata(match, pin->fmd.metadata);
2536     }
2537
2538     for (i = 0; i < FLOW_N_REGS; i++) {
2539         if (pin->fmd.regs[i]) {
2540             match_set_reg(match, i, pin->fmd.regs[i]);
2541         }
2542     }
2543
2544     match_set_in_port(match, pin->fmd.in_port);
2545 }
2546
2547 /* Converts abstract ofputil_packet_in 'pin' into a PACKET_IN message
2548  * in the format specified by 'packet_in_format'.  */
2549 struct ofpbuf *
2550 ofputil_encode_packet_in(const struct ofputil_packet_in *pin,
2551                          enum ofputil_protocol protocol,
2552                          enum nx_packet_in_format packet_in_format)
2553 {
2554     size_t send_len = MIN(pin->send_len, pin->packet_len);
2555     struct ofpbuf *packet;
2556
2557     /* Add OFPT_PACKET_IN. */
2558     if (protocol == OFPUTIL_P_OF13_OXM || protocol == OFPUTIL_P_OF12_OXM) {
2559         struct ofp13_packet_in *opi;
2560         struct match match;
2561         enum ofpraw packet_in_raw;
2562         enum ofp_version packet_in_version;
2563         size_t packet_in_size;
2564
2565         if (protocol == OFPUTIL_P_OF12_OXM) {
2566             packet_in_raw = OFPRAW_OFPT12_PACKET_IN;
2567             packet_in_version = OFP12_VERSION;
2568             packet_in_size = sizeof (struct ofp12_packet_in);
2569         } else {
2570             packet_in_raw = OFPRAW_OFPT13_PACKET_IN;
2571             packet_in_version = OFP13_VERSION;
2572             packet_in_size = sizeof (struct ofp13_packet_in);
2573         }
2574
2575         ofputil_packet_in_to_match(pin, &match);
2576
2577         /* The final argument is just an estimate of the space required. */
2578         packet = ofpraw_alloc_xid(packet_in_raw, packet_in_version,
2579                                   htonl(0), (sizeof(struct flow_metadata) * 2
2580                                              + 2 + send_len));
2581         ofpbuf_put_zeros(packet, packet_in_size);
2582         oxm_put_match(packet, &match);
2583         ofpbuf_put_zeros(packet, 2);
2584         ofpbuf_put(packet, pin->packet, send_len);
2585
2586         opi = packet->l3;
2587         opi->pi.buffer_id = htonl(pin->buffer_id);
2588         opi->pi.total_len = htons(pin->total_len);
2589         opi->pi.reason = pin->reason;
2590         opi->pi.table_id = pin->table_id;
2591         if (protocol == OFPUTIL_P_OF13_OXM) {
2592             opi->cookie = pin->cookie;
2593         }
2594     } else if (packet_in_format == NXPIF_OPENFLOW10) {
2595         struct ofp10_packet_in *opi;
2596
2597         packet = ofpraw_alloc_xid(OFPRAW_OFPT10_PACKET_IN, OFP10_VERSION,
2598                                   htonl(0), send_len);
2599         opi = ofpbuf_put_zeros(packet, offsetof(struct ofp10_packet_in, data));
2600         opi->total_len = htons(pin->total_len);
2601         opi->in_port = htons(pin->fmd.in_port);
2602         opi->reason = pin->reason;
2603         opi->buffer_id = htonl(pin->buffer_id);
2604
2605         ofpbuf_put(packet, pin->packet, send_len);
2606     } else if (packet_in_format == NXPIF_NXM) {
2607         struct nx_packet_in *npi;
2608         struct match match;
2609         size_t match_len;
2610
2611         ofputil_packet_in_to_match(pin, &match);
2612
2613         /* The final argument is just an estimate of the space required. */
2614         packet = ofpraw_alloc_xid(OFPRAW_NXT_PACKET_IN, OFP10_VERSION,
2615                                   htonl(0), (sizeof(struct flow_metadata) * 2
2616                                              + 2 + send_len));
2617         ofpbuf_put_zeros(packet, sizeof *npi);
2618         match_len = nx_put_match(packet, &match, 0, 0);
2619         ofpbuf_put_zeros(packet, 2);
2620         ofpbuf_put(packet, pin->packet, send_len);
2621
2622         npi = packet->l3;
2623         npi->buffer_id = htonl(pin->buffer_id);
2624         npi->total_len = htons(pin->total_len);
2625         npi->reason = pin->reason;
2626         npi->table_id = pin->table_id;
2627         npi->cookie = pin->cookie;
2628         npi->match_len = htons(match_len);
2629     } else {
2630         NOT_REACHED();
2631     }
2632     ofpmsg_update_length(packet);
2633
2634     return packet;
2635 }
2636
2637 const char *
2638 ofputil_packet_in_reason_to_string(enum ofp_packet_in_reason reason)
2639 {
2640     static char s[INT_STRLEN(int) + 1];
2641
2642     switch (reason) {
2643     case OFPR_NO_MATCH:
2644         return "no_match";
2645     case OFPR_ACTION:
2646         return "action";
2647     case OFPR_INVALID_TTL:
2648         return "invalid_ttl";
2649
2650     case OFPR_N_REASONS:
2651     default:
2652         sprintf(s, "%d", (int) reason);
2653         return s;
2654     }
2655 }
2656
2657 bool
2658 ofputil_packet_in_reason_from_string(const char *s,
2659                                      enum ofp_packet_in_reason *reason)
2660 {
2661     int i;
2662
2663     for (i = 0; i < OFPR_N_REASONS; i++) {
2664         if (!strcasecmp(s, ofputil_packet_in_reason_to_string(i))) {
2665             *reason = i;
2666             return true;
2667         }
2668     }
2669     return false;
2670 }
2671
2672 /* Converts an OFPT_PACKET_OUT in 'opo' into an abstract ofputil_packet_out in
2673  * 'po'.
2674  *
2675  * Uses 'ofpacts' to store the abstract OFPACT_* version of the packet out
2676  * message's actions.  The caller must initialize 'ofpacts' and retains
2677  * ownership of it.  'po->ofpacts' will point into the 'ofpacts' buffer.
2678  *
2679  * Returns 0 if successful, otherwise an OFPERR_* value. */
2680 enum ofperr
2681 ofputil_decode_packet_out(struct ofputil_packet_out *po,
2682                           const struct ofp_header *oh,
2683                           struct ofpbuf *ofpacts)
2684 {
2685     enum ofpraw raw;
2686     struct ofpbuf b;
2687
2688     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2689     raw = ofpraw_pull_assert(&b);
2690
2691     if (raw == OFPRAW_OFPT11_PACKET_OUT) {
2692         enum ofperr error;
2693         const struct ofp11_packet_out *opo = ofpbuf_pull(&b, sizeof *opo);
2694
2695         po->buffer_id = ntohl(opo->buffer_id);
2696         error = ofputil_port_from_ofp11(opo->in_port, &po->in_port);
2697         if (error) {
2698             return error;
2699         }
2700
2701         error = ofpacts_pull_openflow11_actions(&b, ntohs(opo->actions_len),
2702                                                 ofpacts);
2703         if (error) {
2704             return error;
2705         }
2706     } else if (raw == OFPRAW_OFPT10_PACKET_OUT) {
2707         enum ofperr error;
2708         const struct ofp10_packet_out *opo = ofpbuf_pull(&b, sizeof *opo);
2709
2710         po->buffer_id = ntohl(opo->buffer_id);
2711         po->in_port = ntohs(opo->in_port);
2712
2713         error = ofpacts_pull_openflow10(&b, ntohs(opo->actions_len), ofpacts);
2714         if (error) {
2715             return error;
2716         }
2717     } else {
2718         NOT_REACHED();
2719     }
2720
2721     if (po->in_port >= OFPP_MAX && po->in_port != OFPP_LOCAL
2722         && po->in_port != OFPP_NONE && po->in_port != OFPP_CONTROLLER) {
2723         VLOG_WARN_RL(&bad_ofmsg_rl, "packet-out has bad input port %#"PRIx16,
2724                      po->in_port);
2725         return OFPERR_OFPBRC_BAD_PORT;
2726     }
2727
2728     po->ofpacts = ofpacts->data;
2729     po->ofpacts_len = ofpacts->size;
2730
2731     if (po->buffer_id == UINT32_MAX) {
2732         po->packet = b.data;
2733         po->packet_len = b.size;
2734     } else {
2735         po->packet = NULL;
2736         po->packet_len = 0;
2737     }
2738
2739     return 0;
2740 }
2741 \f
2742 /* ofputil_phy_port */
2743
2744 /* NETDEV_F_* to and from OFPPF_* and OFPPF10_*. */
2745 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_HD    == OFPPF_10MB_HD);  /* bit 0 */
2746 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_FD    == OFPPF_10MB_FD);  /* bit 1 */
2747 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_HD   == OFPPF_100MB_HD); /* bit 2 */
2748 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_FD   == OFPPF_100MB_FD); /* bit 3 */
2749 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_HD     == OFPPF_1GB_HD);   /* bit 4 */
2750 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_FD     == OFPPF_1GB_FD);   /* bit 5 */
2751 BUILD_ASSERT_DECL((int) NETDEV_F_10GB_FD    == OFPPF_10GB_FD);  /* bit 6 */
2752
2753 /* NETDEV_F_ bits 11...15 are OFPPF10_ bits 7...11: */
2754 BUILD_ASSERT_DECL((int) NETDEV_F_COPPER == (OFPPF10_COPPER << 4));
2755 BUILD_ASSERT_DECL((int) NETDEV_F_FIBER == (OFPPF10_FIBER << 4));
2756 BUILD_ASSERT_DECL((int) NETDEV_F_AUTONEG == (OFPPF10_AUTONEG << 4));
2757 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE == (OFPPF10_PAUSE << 4));
2758 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE_ASYM == (OFPPF10_PAUSE_ASYM << 4));
2759
2760 static enum netdev_features
2761 netdev_port_features_from_ofp10(ovs_be32 ofp10_)
2762 {
2763     uint32_t ofp10 = ntohl(ofp10_);
2764     return (ofp10 & 0x7f) | ((ofp10 & 0xf80) << 4);
2765 }
2766
2767 static ovs_be32
2768 netdev_port_features_to_ofp10(enum netdev_features features)
2769 {
2770     return htonl((features & 0x7f) | ((features & 0xf800) >> 4));
2771 }
2772
2773 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_HD    == OFPPF_10MB_HD);     /* bit 0 */
2774 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_FD    == OFPPF_10MB_FD);     /* bit 1 */
2775 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_HD   == OFPPF_100MB_HD);    /* bit 2 */
2776 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_FD   == OFPPF_100MB_FD);    /* bit 3 */
2777 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_HD     == OFPPF_1GB_HD);      /* bit 4 */
2778 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_FD     == OFPPF_1GB_FD);      /* bit 5 */
2779 BUILD_ASSERT_DECL((int) NETDEV_F_10GB_FD    == OFPPF_10GB_FD);     /* bit 6 */
2780 BUILD_ASSERT_DECL((int) NETDEV_F_40GB_FD    == OFPPF11_40GB_FD);   /* bit 7 */
2781 BUILD_ASSERT_DECL((int) NETDEV_F_100GB_FD   == OFPPF11_100GB_FD);  /* bit 8 */
2782 BUILD_ASSERT_DECL((int) NETDEV_F_1TB_FD     == OFPPF11_1TB_FD);    /* bit 9 */
2783 BUILD_ASSERT_DECL((int) NETDEV_F_OTHER      == OFPPF11_OTHER);     /* bit 10 */
2784 BUILD_ASSERT_DECL((int) NETDEV_F_COPPER     == OFPPF11_COPPER);    /* bit 11 */
2785 BUILD_ASSERT_DECL((int) NETDEV_F_FIBER      == OFPPF11_FIBER);     /* bit 12 */
2786 BUILD_ASSERT_DECL((int) NETDEV_F_AUTONEG    == OFPPF11_AUTONEG);   /* bit 13 */
2787 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE      == OFPPF11_PAUSE);     /* bit 14 */
2788 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE_ASYM == OFPPF11_PAUSE_ASYM);/* bit 15 */
2789
2790 static enum netdev_features
2791 netdev_port_features_from_ofp11(ovs_be32 ofp11)
2792 {
2793     return ntohl(ofp11) & 0xffff;
2794 }
2795
2796 static ovs_be32
2797 netdev_port_features_to_ofp11(enum netdev_features features)
2798 {
2799     return htonl(features & 0xffff);
2800 }
2801
2802 static enum ofperr
2803 ofputil_decode_ofp10_phy_port(struct ofputil_phy_port *pp,
2804                               const struct ofp10_phy_port *opp)
2805 {
2806     memset(pp, 0, sizeof *pp);
2807
2808     pp->port_no = ntohs(opp->port_no);
2809     memcpy(pp->hw_addr, opp->hw_addr, OFP_ETH_ALEN);
2810     ovs_strlcpy(pp->name, opp->name, OFP_MAX_PORT_NAME_LEN);
2811
2812     pp->config = ntohl(opp->config) & OFPPC10_ALL;
2813     pp->state = ntohl(opp->state) & OFPPS10_ALL;
2814
2815     pp->curr = netdev_port_features_from_ofp10(opp->curr);
2816     pp->advertised = netdev_port_features_from_ofp10(opp->advertised);
2817     pp->supported = netdev_port_features_from_ofp10(opp->supported);
2818     pp->peer = netdev_port_features_from_ofp10(opp->peer);
2819
2820     pp->curr_speed = netdev_features_to_bps(pp->curr, 0) / 1000;
2821     pp->max_speed = netdev_features_to_bps(pp->supported, 0) / 1000;
2822
2823     return 0;
2824 }
2825
2826 static enum ofperr
2827 ofputil_decode_ofp11_port(struct ofputil_phy_port *pp,
2828                           const struct ofp11_port *op)
2829 {
2830     enum ofperr error;
2831
2832     memset(pp, 0, sizeof *pp);
2833
2834     error = ofputil_port_from_ofp11(op->port_no, &pp->port_no);
2835     if (error) {
2836         return error;
2837     }
2838     memcpy(pp->hw_addr, op->hw_addr, OFP_ETH_ALEN);
2839     ovs_strlcpy(pp->name, op->name, OFP_MAX_PORT_NAME_LEN);
2840
2841     pp->config = ntohl(op->config) & OFPPC11_ALL;
2842     pp->state = ntohl(op->state) & OFPPC11_ALL;
2843
2844     pp->curr = netdev_port_features_from_ofp11(op->curr);
2845     pp->advertised = netdev_port_features_from_ofp11(op->advertised);
2846     pp->supported = netdev_port_features_from_ofp11(op->supported);
2847     pp->peer = netdev_port_features_from_ofp11(op->peer);
2848
2849     pp->curr_speed = ntohl(op->curr_speed);
2850     pp->max_speed = ntohl(op->max_speed);
2851
2852     return 0;
2853 }
2854
2855 static size_t
2856 ofputil_get_phy_port_size(enum ofp_version ofp_version)
2857 {
2858     switch (ofp_version) {
2859     case OFP10_VERSION:
2860         return sizeof(struct ofp10_phy_port);
2861     case OFP11_VERSION:
2862     case OFP12_VERSION:
2863     case OFP13_VERSION:
2864         return sizeof(struct ofp11_port);
2865     default:
2866         NOT_REACHED();
2867     }
2868 }
2869
2870 static void
2871 ofputil_encode_ofp10_phy_port(const struct ofputil_phy_port *pp,
2872                               struct ofp10_phy_port *opp)
2873 {
2874     memset(opp, 0, sizeof *opp);
2875
2876     opp->port_no = htons(pp->port_no);
2877     memcpy(opp->hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2878     ovs_strlcpy(opp->name, pp->name, OFP_MAX_PORT_NAME_LEN);
2879
2880     opp->config = htonl(pp->config & OFPPC10_ALL);
2881     opp->state = htonl(pp->state & OFPPS10_ALL);
2882
2883     opp->curr = netdev_port_features_to_ofp10(pp->curr);
2884     opp->advertised = netdev_port_features_to_ofp10(pp->advertised);
2885     opp->supported = netdev_port_features_to_ofp10(pp->supported);
2886     opp->peer = netdev_port_features_to_ofp10(pp->peer);
2887 }
2888
2889 static void
2890 ofputil_encode_ofp11_port(const struct ofputil_phy_port *pp,
2891                           struct ofp11_port *op)
2892 {
2893     memset(op, 0, sizeof *op);
2894
2895     op->port_no = ofputil_port_to_ofp11(pp->port_no);
2896     memcpy(op->hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2897     ovs_strlcpy(op->name, pp->name, OFP_MAX_PORT_NAME_LEN);
2898
2899     op->config = htonl(pp->config & OFPPC11_ALL);
2900     op->state = htonl(pp->state & OFPPS11_ALL);
2901
2902     op->curr = netdev_port_features_to_ofp11(pp->curr);
2903     op->advertised = netdev_port_features_to_ofp11(pp->advertised);
2904     op->supported = netdev_port_features_to_ofp11(pp->supported);
2905     op->peer = netdev_port_features_to_ofp11(pp->peer);
2906
2907     op->curr_speed = htonl(pp->curr_speed);
2908     op->max_speed = htonl(pp->max_speed);
2909 }
2910
2911 static void
2912 ofputil_put_phy_port(enum ofp_version ofp_version,
2913                      const struct ofputil_phy_port *pp, struct ofpbuf *b)
2914 {
2915     switch (ofp_version) {
2916     case OFP10_VERSION: {
2917         struct ofp10_phy_port *opp;
2918         if (b->size + sizeof *opp <= UINT16_MAX) {
2919             opp = ofpbuf_put_uninit(b, sizeof *opp);
2920             ofputil_encode_ofp10_phy_port(pp, opp);
2921         }
2922         break;
2923     }
2924
2925     case OFP11_VERSION:
2926     case OFP12_VERSION:
2927     case OFP13_VERSION: {
2928         struct ofp11_port *op;
2929         if (b->size + sizeof *op <= UINT16_MAX) {
2930             op = ofpbuf_put_uninit(b, sizeof *op);
2931             ofputil_encode_ofp11_port(pp, op);
2932         }
2933         break;
2934     }
2935
2936     default:
2937         NOT_REACHED();
2938     }
2939 }
2940
2941 void
2942 ofputil_append_port_desc_stats_reply(enum ofp_version ofp_version,
2943                                      const struct ofputil_phy_port *pp,
2944                                      struct list *replies)
2945 {
2946     switch (ofp_version) {
2947     case OFP10_VERSION: {
2948         struct ofp10_phy_port *opp;
2949
2950         opp = ofpmp_append(replies, sizeof *opp);
2951         ofputil_encode_ofp10_phy_port(pp, opp);
2952         break;
2953     }
2954
2955     case OFP11_VERSION:
2956     case OFP12_VERSION:
2957     case OFP13_VERSION: {
2958         struct ofp11_port *op;
2959
2960         op = ofpmp_append(replies, sizeof *op);
2961         ofputil_encode_ofp11_port(pp, op);
2962         break;
2963     }
2964
2965     default:
2966       NOT_REACHED();
2967     }
2968 }
2969 \f
2970 /* ofputil_switch_features */
2971
2972 #define OFPC_COMMON (OFPC_FLOW_STATS | OFPC_TABLE_STATS | OFPC_PORT_STATS | \
2973                      OFPC_IP_REASM | OFPC_QUEUE_STATS)
2974 BUILD_ASSERT_DECL((int) OFPUTIL_C_FLOW_STATS == OFPC_FLOW_STATS);
2975 BUILD_ASSERT_DECL((int) OFPUTIL_C_TABLE_STATS == OFPC_TABLE_STATS);
2976 BUILD_ASSERT_DECL((int) OFPUTIL_C_PORT_STATS == OFPC_PORT_STATS);
2977 BUILD_ASSERT_DECL((int) OFPUTIL_C_IP_REASM == OFPC_IP_REASM);
2978 BUILD_ASSERT_DECL((int) OFPUTIL_C_QUEUE_STATS == OFPC_QUEUE_STATS);
2979 BUILD_ASSERT_DECL((int) OFPUTIL_C_ARP_MATCH_IP == OFPC_ARP_MATCH_IP);
2980
2981 struct ofputil_action_bit_translation {
2982     enum ofputil_action_bitmap ofputil_bit;
2983     int of_bit;
2984 };
2985
2986 static const struct ofputil_action_bit_translation of10_action_bits[] = {
2987     { OFPUTIL_A_OUTPUT,       OFPAT10_OUTPUT },
2988     { OFPUTIL_A_SET_VLAN_VID, OFPAT10_SET_VLAN_VID },
2989     { OFPUTIL_A_SET_VLAN_PCP, OFPAT10_SET_VLAN_PCP },
2990     { OFPUTIL_A_STRIP_VLAN,   OFPAT10_STRIP_VLAN },
2991     { OFPUTIL_A_SET_DL_SRC,   OFPAT10_SET_DL_SRC },
2992     { OFPUTIL_A_SET_DL_DST,   OFPAT10_SET_DL_DST },
2993     { OFPUTIL_A_SET_NW_SRC,   OFPAT10_SET_NW_SRC },
2994     { OFPUTIL_A_SET_NW_DST,   OFPAT10_SET_NW_DST },
2995     { OFPUTIL_A_SET_NW_TOS,   OFPAT10_SET_NW_TOS },
2996     { OFPUTIL_A_SET_TP_SRC,   OFPAT10_SET_TP_SRC },
2997     { OFPUTIL_A_SET_TP_DST,   OFPAT10_SET_TP_DST },
2998     { OFPUTIL_A_ENQUEUE,      OFPAT10_ENQUEUE },
2999     { 0, 0 },
3000 };
3001
3002 static enum ofputil_action_bitmap
3003 decode_action_bits(ovs_be32 of_actions,
3004                    const struct ofputil_action_bit_translation *x)
3005 {
3006     enum ofputil_action_bitmap ofputil_actions;
3007
3008     ofputil_actions = 0;
3009     for (; x->ofputil_bit; x++) {
3010         if (of_actions & htonl(1u << x->of_bit)) {
3011             ofputil_actions |= x->ofputil_bit;
3012         }
3013     }
3014     return ofputil_actions;
3015 }
3016
3017 static uint32_t
3018 ofputil_capabilities_mask(enum ofp_version ofp_version)
3019 {
3020     /* Handle capabilities whose bit is unique for all Open Flow versions */
3021     switch (ofp_version) {
3022     case OFP10_VERSION:
3023     case OFP11_VERSION:
3024         return OFPC_COMMON | OFPC_ARP_MATCH_IP;
3025     case OFP12_VERSION:
3026     case OFP13_VERSION:
3027         return OFPC_COMMON | OFPC12_PORT_BLOCKED;
3028     default:
3029         /* Caller needs to check osf->header.version itself */
3030         return 0;
3031     }
3032 }
3033
3034 /* Decodes an OpenFlow 1.0 or 1.1 "switch_features" structure 'osf' into an
3035  * abstract representation in '*features'.  Initializes '*b' to iterate over
3036  * the OpenFlow port structures following 'osf' with later calls to
3037  * ofputil_pull_phy_port().  Returns 0 if successful, otherwise an
3038  * OFPERR_* value.  */
3039 enum ofperr
3040 ofputil_decode_switch_features(const struct ofp_header *oh,
3041                                struct ofputil_switch_features *features,
3042                                struct ofpbuf *b)
3043 {
3044     const struct ofp_switch_features *osf;
3045     enum ofpraw raw;
3046
3047     ofpbuf_use_const(b, oh, ntohs(oh->length));
3048     raw = ofpraw_pull_assert(b);
3049
3050     osf = ofpbuf_pull(b, sizeof *osf);
3051     features->datapath_id = ntohll(osf->datapath_id);
3052     features->n_buffers = ntohl(osf->n_buffers);
3053     features->n_tables = osf->n_tables;
3054     features->auxiliary_id = 0;
3055
3056     features->capabilities = ntohl(osf->capabilities) &
3057         ofputil_capabilities_mask(oh->version);
3058
3059     if (b->size % ofputil_get_phy_port_size(oh->version)) {
3060         return OFPERR_OFPBRC_BAD_LEN;
3061     }
3062
3063     if (raw == OFPRAW_OFPT10_FEATURES_REPLY) {
3064         if (osf->capabilities & htonl(OFPC10_STP)) {
3065             features->capabilities |= OFPUTIL_C_STP;
3066         }
3067         features->actions = decode_action_bits(osf->actions, of10_action_bits);
3068     } else if (raw == OFPRAW_OFPT11_FEATURES_REPLY
3069                || raw == OFPRAW_OFPT13_FEATURES_REPLY) {
3070         if (osf->capabilities & htonl(OFPC11_GROUP_STATS)) {
3071             features->capabilities |= OFPUTIL_C_GROUP_STATS;
3072         }
3073         features->actions = 0;
3074         if (raw == OFPRAW_OFPT13_FEATURES_REPLY) {
3075             features->auxiliary_id = osf->auxiliary_id;
3076         }
3077     } else {
3078         return OFPERR_OFPBRC_BAD_VERSION;
3079     }
3080
3081     return 0;
3082 }
3083
3084 /* Returns true if the maximum number of ports are in 'oh'. */
3085 static bool
3086 max_ports_in_features(const struct ofp_header *oh)
3087 {
3088     size_t pp_size = ofputil_get_phy_port_size(oh->version);
3089     return ntohs(oh->length) + pp_size > UINT16_MAX;
3090 }
3091
3092 /* Given a buffer 'b' that contains a Features Reply message, checks if
3093  * it contains the maximum number of ports that will fit.  If so, it
3094  * returns true and removes the ports from the message.  The caller
3095  * should then send an OFPST_PORT_DESC stats request to get the ports,
3096  * since the switch may have more ports than could be represented in the
3097  * Features Reply.  Otherwise, returns false.
3098  */
3099 bool
3100 ofputil_switch_features_ports_trunc(struct ofpbuf *b)
3101 {
3102     struct ofp_header *oh = b->data;
3103
3104     if (max_ports_in_features(oh)) {
3105         /* Remove all the ports. */
3106         b->size = (sizeof(struct ofp_header)
3107                    + sizeof(struct ofp_switch_features));
3108         ofpmsg_update_length(b);
3109
3110         return true;
3111     }
3112
3113     return false;
3114 }
3115
3116 static ovs_be32
3117 encode_action_bits(enum ofputil_action_bitmap ofputil_actions,
3118                    const struct ofputil_action_bit_translation *x)
3119 {
3120     uint32_t of_actions;
3121
3122     of_actions = 0;
3123     for (; x->ofputil_bit; x++) {
3124         if (ofputil_actions & x->ofputil_bit) {
3125             of_actions |= 1 << x->of_bit;
3126         }
3127     }
3128     return htonl(of_actions);
3129 }
3130
3131 /* Returns a buffer owned by the caller that encodes 'features' in the format
3132  * required by 'protocol' with the given 'xid'.  The caller should append port
3133  * information to the buffer with subsequent calls to
3134  * ofputil_put_switch_features_port(). */
3135 struct ofpbuf *
3136 ofputil_encode_switch_features(const struct ofputil_switch_features *features,
3137                                enum ofputil_protocol protocol, ovs_be32 xid)
3138 {
3139     struct ofp_switch_features *osf;
3140     struct ofpbuf *b;
3141     enum ofp_version version;
3142     enum ofpraw raw;
3143
3144     version = ofputil_protocol_to_ofp_version(protocol);
3145     switch (version) {
3146     case OFP10_VERSION:
3147         raw = OFPRAW_OFPT10_FEATURES_REPLY;
3148         break;
3149     case OFP11_VERSION:
3150     case OFP12_VERSION:
3151         raw = OFPRAW_OFPT11_FEATURES_REPLY;
3152         break;
3153     case OFP13_VERSION:
3154         raw = OFPRAW_OFPT13_FEATURES_REPLY;
3155         break;
3156     default:
3157         NOT_REACHED();
3158     }
3159     b = ofpraw_alloc_xid(raw, version, xid, 0);
3160     osf = ofpbuf_put_zeros(b, sizeof *osf);
3161     osf->datapath_id = htonll(features->datapath_id);
3162     osf->n_buffers = htonl(features->n_buffers);
3163     osf->n_tables = features->n_tables;
3164
3165     osf->capabilities = htonl(features->capabilities & OFPC_COMMON);
3166     osf->capabilities = htonl(features->capabilities &
3167                               ofputil_capabilities_mask(version));
3168     switch (version) {
3169     case OFP10_VERSION:
3170         if (features->capabilities & OFPUTIL_C_STP) {
3171             osf->capabilities |= htonl(OFPC10_STP);
3172         }
3173         osf->actions = encode_action_bits(features->actions, of10_action_bits);
3174         break;
3175     case OFP13_VERSION:
3176         osf->auxiliary_id = features->auxiliary_id;
3177         /* fall through */
3178     case OFP11_VERSION:
3179     case OFP12_VERSION:
3180         if (features->capabilities & OFPUTIL_C_GROUP_STATS) {
3181             osf->capabilities |= htonl(OFPC11_GROUP_STATS);
3182         }
3183         break;
3184     default:
3185         NOT_REACHED();
3186     }
3187
3188     return b;
3189 }
3190
3191 /* Encodes 'pp' into the format required by the switch_features message already
3192  * in 'b', which should have been returned by ofputil_encode_switch_features(),
3193  * and appends the encoded version to 'b'. */
3194 void
3195 ofputil_put_switch_features_port(const struct ofputil_phy_port *pp,
3196                                  struct ofpbuf *b)
3197 {
3198     const struct ofp_header *oh = b->data;
3199
3200     if (oh->version < OFP13_VERSION) {
3201         ofputil_put_phy_port(oh->version, pp, b);
3202     }
3203 }
3204 \f
3205 /* ofputil_port_status */
3206
3207 /* Decodes the OpenFlow "port status" message in '*ops' into an abstract form
3208  * in '*ps'.  Returns 0 if successful, otherwise an OFPERR_* value. */
3209 enum ofperr
3210 ofputil_decode_port_status(const struct ofp_header *oh,
3211                            struct ofputil_port_status *ps)
3212 {
3213     const struct ofp_port_status *ops;
3214     struct ofpbuf b;
3215     int retval;
3216
3217     ofpbuf_use_const(&b, oh, ntohs(oh->length));
3218     ofpraw_pull_assert(&b);
3219     ops = ofpbuf_pull(&b, sizeof *ops);
3220
3221     if (ops->reason != OFPPR_ADD &&
3222         ops->reason != OFPPR_DELETE &&
3223         ops->reason != OFPPR_MODIFY) {
3224         return OFPERR_NXBRC_BAD_REASON;
3225     }
3226     ps->reason = ops->reason;
3227
3228     retval = ofputil_pull_phy_port(oh->version, &b, &ps->desc);
3229     ovs_assert(retval != EOF);
3230     return retval;
3231 }
3232
3233 /* Converts the abstract form of a "port status" message in '*ps' into an
3234  * OpenFlow message suitable for 'protocol', and returns that encoded form in
3235  * a buffer owned by the caller. */
3236 struct ofpbuf *
3237 ofputil_encode_port_status(const struct ofputil_port_status *ps,
3238                            enum ofputil_protocol protocol)
3239 {
3240     struct ofp_port_status *ops;
3241     struct ofpbuf *b;
3242     enum ofp_version version;
3243     enum ofpraw raw;
3244
3245     version = ofputil_protocol_to_ofp_version(protocol);
3246     switch (version) {
3247     case OFP10_VERSION:
3248         raw = OFPRAW_OFPT10_PORT_STATUS;
3249         break;
3250
3251     case OFP11_VERSION:
3252     case OFP12_VERSION:
3253     case OFP13_VERSION:
3254         raw = OFPRAW_OFPT11_PORT_STATUS;
3255         break;
3256
3257     default:
3258         NOT_REACHED();
3259     }
3260
3261     b = ofpraw_alloc_xid(raw, version, htonl(0), 0);
3262     ops = ofpbuf_put_zeros(b, sizeof *ops);
3263     ops->reason = ps->reason;
3264     ofputil_put_phy_port(version, &ps->desc, b);
3265     ofpmsg_update_length(b);
3266     return b;
3267 }
3268 \f
3269 /* ofputil_port_mod */
3270
3271 /* Decodes the OpenFlow "port mod" message in '*oh' into an abstract form in
3272  * '*pm'.  Returns 0 if successful, otherwise an OFPERR_* value. */
3273 enum ofperr
3274 ofputil_decode_port_mod(const struct ofp_header *oh,
3275                         struct ofputil_port_mod *pm)
3276 {
3277     enum ofpraw raw;
3278     struct ofpbuf b;
3279
3280     ofpbuf_use_const(&b, oh, ntohs(oh->length));
3281     raw = ofpraw_pull_assert(&b);
3282
3283     if (raw == OFPRAW_OFPT10_PORT_MOD) {
3284         const struct ofp10_port_mod *opm = b.data;
3285
3286         pm->port_no = ntohs(opm->port_no);
3287         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
3288         pm->config = ntohl(opm->config) & OFPPC10_ALL;
3289         pm->mask = ntohl(opm->mask) & OFPPC10_ALL;
3290         pm->advertise = netdev_port_features_from_ofp10(opm->advertise);
3291     } else if (raw == OFPRAW_OFPT11_PORT_MOD) {
3292         const struct ofp11_port_mod *opm = b.data;
3293         enum ofperr error;
3294
3295         error = ofputil_port_from_ofp11(opm->port_no, &pm->port_no);
3296         if (error) {
3297             return error;
3298         }
3299
3300         memcpy(pm->hw_addr, opm->hw_addr, ETH_ADDR_LEN);
3301         pm->config = ntohl(opm->config) & OFPPC11_ALL;
3302         pm->mask = ntohl(opm->mask) & OFPPC11_ALL;
3303         pm->advertise = netdev_port_features_from_ofp11(opm->advertise);
3304     } else {
3305         return OFPERR_OFPBRC_BAD_TYPE;
3306     }
3307
3308     pm->config &= pm->mask;
3309     return 0;
3310 }
3311
3312 /* Converts the abstract form of a "port mod" message in '*pm' into an OpenFlow
3313  * message suitable for 'protocol', and returns that encoded form in a buffer
3314  * owned by the caller. */
3315 struct ofpbuf *
3316 ofputil_encode_port_mod(const struct ofputil_port_mod *pm,
3317                         enum ofputil_protocol protocol)
3318 {
3319     enum ofp_version ofp_version = ofputil_protocol_to_ofp_version(protocol);
3320     struct ofpbuf *b;
3321
3322     switch (ofp_version) {
3323     case OFP10_VERSION: {
3324         struct ofp10_port_mod *opm;
3325
3326         b = ofpraw_alloc(OFPRAW_OFPT10_PORT_MOD, ofp_version, 0);
3327         opm = ofpbuf_put_zeros(b, sizeof *opm);
3328         opm->port_no = htons(pm->port_no);
3329         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
3330         opm->config = htonl(pm->config & OFPPC10_ALL);
3331         opm->mask = htonl(pm->mask & OFPPC10_ALL);
3332         opm->advertise = netdev_port_features_to_ofp10(pm->advertise);
3333         break;
3334     }
3335
3336     case OFP11_VERSION:
3337     case OFP12_VERSION:
3338     case OFP13_VERSION: {
3339         struct ofp11_port_mod *opm;
3340
3341         b = ofpraw_alloc(OFPRAW_OFPT11_PORT_MOD, ofp_version, 0);
3342         opm = ofpbuf_put_zeros(b, sizeof *opm);
3343         opm->port_no = ofputil_port_to_ofp11(pm->port_no);
3344         memcpy(opm->hw_addr, pm->hw_addr, ETH_ADDR_LEN);
3345         opm->config = htonl(pm->config & OFPPC11_ALL);
3346         opm->mask = htonl(pm->mask & OFPPC11_ALL);
3347         opm->advertise = netdev_port_features_to_ofp11(pm->advertise);
3348         break;
3349     }
3350
3351     default:
3352         NOT_REACHED();
3353     }
3354
3355     return b;
3356 }
3357 \f
3358 /* ofputil_role_request */
3359
3360 /* Decodes the OpenFlow "role request" or "role reply" message in '*oh' into
3361  * an abstract form in '*rr'.  Returns 0 if successful, otherwise an
3362  * OFPERR_* value. */
3363 enum ofperr
3364 ofputil_decode_role_message(const struct ofp_header *oh,
3365                             struct ofputil_role_request *rr)
3366 {
3367     const struct ofp12_role_request *orr = ofpmsg_body(oh);
3368     uint32_t role = ntohl(orr->role);
3369     struct ofpbuf b;
3370     enum ofpraw raw;
3371
3372     memset(rr, 0, sizeof *rr);
3373
3374     ofpbuf_use_const(&b, oh, ntohs(oh->length));
3375     raw = ofpraw_pull_assert(&b);
3376
3377     if (raw == OFPRAW_OFPT12_ROLE_REQUEST
3378         || raw == OFPRAW_OFPT12_ROLE_REPLY) {
3379
3380         if (raw == OFPRAW_OFPT12_ROLE_REQUEST) {
3381             if (role == OFPCR12_ROLE_NOCHANGE) {
3382                 rr->request_current_role_only = true;
3383                 return 0;
3384             }
3385             if (role == OFPCR12_ROLE_MASTER || role == OFPCR12_ROLE_SLAVE) {
3386                 rr->generation_id = ntohll(orr->generation_id);
3387                 rr->have_generation_id = true;
3388             }
3389         }
3390
3391         /* Map to enum nx_role */
3392         role -= 1; /* OFPCR12_ROLE_MASTER -> NX_ROLE_MASTER etc. */
3393     } else if (raw != OFPRAW_NXT_ROLE_REQUEST
3394                && raw != OFPRAW_NXT_ROLE_REPLY) {
3395         return OFPERR_OFPBRC_BAD_TYPE;
3396     }
3397
3398     if (role != NX_ROLE_OTHER && role != NX_ROLE_MASTER
3399         && role != NX_ROLE_SLAVE) {
3400         return OFPERR_OFPRRFC_BAD_ROLE;
3401     }
3402
3403     rr->role = role;
3404     return 0;
3405 }
3406
3407 /* Returns an encoded form of a role reply suitable for the "request" in a
3408  * buffer owned by the caller. */
3409 struct ofpbuf *
3410 ofputil_encode_role_reply(const struct ofp_header *request,
3411                           enum nx_role role)
3412 {
3413     struct ofp12_role_request *reply;
3414     struct ofpbuf *buf;
3415     size_t reply_size;
3416
3417     struct ofpbuf b;
3418     enum ofpraw raw;
3419
3420     ofpbuf_use_const(&b, request, ntohs(request->length));
3421     raw = ofpraw_pull_assert(&b);
3422     if (raw == OFPRAW_OFPT12_ROLE_REQUEST) {
3423         reply_size = sizeof (struct ofp12_role_request);
3424         raw = OFPRAW_OFPT12_ROLE_REPLY;
3425     }
3426     else if (raw == OFPRAW_NXT_ROLE_REQUEST) {
3427         reply_size = sizeof (struct nx_role_request);
3428         raw = OFPRAW_NXT_ROLE_REPLY;
3429     } else {
3430         NOT_REACHED();
3431     }
3432
3433     buf = ofpraw_alloc_reply(raw, request, 0);
3434     reply = ofpbuf_put_zeros(buf, reply_size);
3435
3436     if (raw == OFPRAW_OFPT12_ROLE_REPLY) {
3437         /* Map to OpenFlow enum ofp12_controller_role */
3438         role += 1; /* NX_ROLE_MASTER -> OFPCR12_ROLE_MASTER etc. */
3439         /*
3440          * OpenFlow specification does not specify use of generation_id field
3441          * on reply messages.  Intuitively, it would seem a good idea to return
3442          * the current value.  However, the current value is undefined
3443          * initially, and there is no way to insert an undefined value in the
3444          * message.  Therefore we leave the generation_id zeroed on reply
3445          * messages.
3446          *
3447          * A request for clarification has been filed with the Open Networking
3448          * Foundation as EXT-272.
3449          */
3450     }
3451     reply->role = htonl(role);
3452
3453     return buf;
3454 }
3455 \f
3456 /* Table stats. */
3457
3458 static void
3459 ofputil_put_ofp10_table_stats(const struct ofp12_table_stats *in,
3460                               struct ofpbuf *buf)
3461 {
3462     struct wc_map {
3463         enum ofp10_flow_wildcards wc10;
3464         enum oxm12_ofb_match_fields mf12;
3465     };
3466
3467     static const struct wc_map wc_map[] = {
3468         { OFPFW10_IN_PORT,     OFPXMT12_OFB_IN_PORT },
3469         { OFPFW10_DL_VLAN,     OFPXMT12_OFB_VLAN_VID },
3470         { OFPFW10_DL_SRC,      OFPXMT12_OFB_ETH_SRC },
3471         { OFPFW10_DL_DST,      OFPXMT12_OFB_ETH_DST},
3472         { OFPFW10_DL_TYPE,     OFPXMT12_OFB_ETH_TYPE },
3473         { OFPFW10_NW_PROTO,    OFPXMT12_OFB_IP_PROTO },
3474         { OFPFW10_TP_SRC,      OFPXMT12_OFB_TCP_SRC },
3475         { OFPFW10_TP_DST,      OFPXMT12_OFB_TCP_DST },
3476         { OFPFW10_NW_SRC_MASK, OFPXMT12_OFB_IPV4_SRC },
3477         { OFPFW10_NW_DST_MASK, OFPXMT12_OFB_IPV4_DST },
3478         { OFPFW10_DL_VLAN_PCP, OFPXMT12_OFB_VLAN_PCP },
3479         { OFPFW10_NW_TOS,      OFPXMT12_OFB_IP_DSCP },
3480     };
3481
3482     struct ofp10_table_stats *out;
3483     const struct wc_map *p;
3484
3485     out = ofpbuf_put_zeros(buf, sizeof *out);
3486     out->table_id = in->table_id;
3487     ovs_strlcpy(out->name, in->name, sizeof out->name);
3488     out->wildcards = 0;
3489     for (p = wc_map; p < &wc_map[ARRAY_SIZE(wc_map)]; p++) {
3490         if (in->wildcards & htonll(1ULL << p->mf12)) {
3491             out->wildcards |= htonl(p->wc10);
3492         }
3493     }
3494     out->max_entries = in->max_entries;
3495     out->active_count = in->active_count;
3496     put_32aligned_be64(&out->lookup_count, in->lookup_count);
3497     put_32aligned_be64(&out->matched_count, in->matched_count);
3498 }
3499
3500 static ovs_be32
3501 oxm12_to_ofp11_flow_match_fields(ovs_be64 oxm12)
3502 {
3503     struct map {
3504         enum ofp11_flow_match_fields fmf11;
3505         enum oxm12_ofb_match_fields mf12;
3506     };
3507
3508     static const struct map map[] = {
3509         { OFPFMF11_IN_PORT,     OFPXMT12_OFB_IN_PORT },
3510         { OFPFMF11_DL_VLAN,     OFPXMT12_OFB_VLAN_VID },
3511         { OFPFMF11_DL_VLAN_PCP, OFPXMT12_OFB_VLAN_PCP },
3512         { OFPFMF11_DL_TYPE,     OFPXMT12_OFB_ETH_TYPE },
3513         { OFPFMF11_NW_TOS,      OFPXMT12_OFB_IP_DSCP },
3514         { OFPFMF11_NW_PROTO,    OFPXMT12_OFB_IP_PROTO },
3515         { OFPFMF11_TP_SRC,      OFPXMT12_OFB_TCP_SRC },
3516         { OFPFMF11_TP_DST,      OFPXMT12_OFB_TCP_DST },
3517         { OFPFMF11_MPLS_LABEL,  OFPXMT12_OFB_MPLS_LABEL },
3518         { OFPFMF11_MPLS_TC,     OFPXMT12_OFB_MPLS_TC },
3519         /* I don't know what OFPFMF11_TYPE means. */
3520         { OFPFMF11_DL_SRC,      OFPXMT12_OFB_ETH_SRC },
3521         { OFPFMF11_DL_DST,      OFPXMT12_OFB_ETH_DST },
3522         { OFPFMF11_NW_SRC,      OFPXMT12_OFB_IPV4_SRC },
3523         { OFPFMF11_NW_DST,      OFPXMT12_OFB_IPV4_DST },
3524         { OFPFMF11_METADATA,    OFPXMT12_OFB_METADATA },
3525     };
3526
3527     const struct map *p;
3528     uint32_t fmf11;
3529
3530     fmf11 = 0;
3531     for (p = map; p < &map[ARRAY_SIZE(map)]; p++) {
3532         if (oxm12 & htonll(1ULL << p->mf12)) {
3533             fmf11 |= p->fmf11;
3534         }
3535     }
3536     return htonl(fmf11);
3537 }
3538
3539 static void
3540 ofputil_put_ofp11_table_stats(const struct ofp12_table_stats *in,
3541                               struct ofpbuf *buf)
3542 {
3543     struct ofp11_table_stats *out;
3544
3545     out = ofpbuf_put_zeros(buf, sizeof *out);
3546     out->table_id = in->table_id;
3547     ovs_strlcpy(out->name, in->name, sizeof out->name);
3548     out->wildcards = oxm12_to_ofp11_flow_match_fields(in->wildcards);
3549     out->match = oxm12_to_ofp11_flow_match_fields(in->match);
3550     out->instructions = in->instructions;
3551     out->write_actions = in->write_actions;
3552     out->apply_actions = in->apply_actions;
3553     out->config = in->config;
3554     out->max_entries = in->max_entries;
3555     out->active_count = in->active_count;
3556     out->lookup_count = in->lookup_count;
3557     out->matched_count = in->matched_count;
3558 }
3559
3560 static void
3561 ofputil_put_ofp13_table_stats(const struct ofp12_table_stats *in,
3562                               struct ofpbuf *buf)
3563 {
3564     struct ofp13_table_stats *out;
3565
3566     /* OF 1.3 splits table features off the ofp_table_stats,
3567      * so there is not much here. */
3568
3569     out = ofpbuf_put_uninit(buf, sizeof *out);
3570     out->table_id = in->table_id;
3571     out->active_count = in->active_count;
3572     out->lookup_count = in->lookup_count;
3573     out->matched_count = in->matched_count;
3574 }
3575
3576 struct ofpbuf *
3577 ofputil_encode_table_stats_reply(const struct ofp12_table_stats stats[], int n,
3578                                  const struct ofp_header *request)
3579 {
3580     struct ofpbuf *reply;
3581     int i;
3582
3583     reply = ofpraw_alloc_stats_reply(request, n * sizeof *stats);
3584
3585     switch ((enum ofp_version) request->version) {
3586     case OFP10_VERSION:
3587         for (i = 0; i < n; i++) {
3588             ofputil_put_ofp10_table_stats(&stats[i], reply);
3589         }
3590         break;
3591
3592     case OFP11_VERSION:
3593         for (i = 0; i < n; i++) {
3594             ofputil_put_ofp11_table_stats(&stats[i], reply);
3595         }
3596         break;
3597
3598     case OFP12_VERSION:
3599         ofpbuf_put(reply, stats, n * sizeof *stats);
3600         break;
3601
3602     case OFP13_VERSION:
3603         for (i = 0; i < n; i++) {
3604             ofputil_put_ofp13_table_stats(&stats[i], reply);
3605         }
3606         break;
3607
3608     default:
3609         NOT_REACHED();
3610     }
3611
3612     return reply;
3613 }
3614 \f
3615 /* ofputil_flow_monitor_request */
3616
3617 /* Converts an NXST_FLOW_MONITOR request in 'msg' into an abstract
3618  * ofputil_flow_monitor_request in 'rq'.
3619  *
3620  * Multiple NXST_FLOW_MONITOR requests can be packed into a single OpenFlow
3621  * message.  Calling this function multiple times for a single 'msg' iterates
3622  * through the requests.  The caller must initially leave 'msg''s layer
3623  * pointers null and not modify them between calls.
3624  *
3625  * Returns 0 if successful, EOF if no requests were left in this 'msg',
3626  * otherwise an OFPERR_* value. */
3627 int
3628 ofputil_decode_flow_monitor_request(struct ofputil_flow_monitor_request *rq,
3629                                     struct ofpbuf *msg)
3630 {
3631     struct nx_flow_monitor_request *nfmr;
3632     uint16_t flags;
3633
3634     if (!msg->l2) {
3635         msg->l2 = msg->data;
3636         ofpraw_pull_assert(msg);
3637     }
3638
3639     if (!msg->size) {
3640         return EOF;
3641     }
3642
3643     nfmr = ofpbuf_try_pull(msg, sizeof *nfmr);
3644     if (!nfmr) {
3645         VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR request has %zu "
3646                      "leftover bytes at end", msg->size);
3647         return OFPERR_OFPBRC_BAD_LEN;
3648     }
3649
3650     flags = ntohs(nfmr->flags);
3651     if (!(flags & (NXFMF_ADD | NXFMF_DELETE | NXFMF_MODIFY))
3652         || flags & ~(NXFMF_INITIAL | NXFMF_ADD | NXFMF_DELETE
3653                      | NXFMF_MODIFY | NXFMF_ACTIONS | NXFMF_OWN)) {
3654         VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR has bad flags %#"PRIx16,
3655                      flags);
3656         return OFPERR_NXBRC_FM_BAD_FLAGS;
3657     }
3658
3659     if (!is_all_zeros(nfmr->zeros, sizeof nfmr->zeros)) {
3660         return OFPERR_NXBRC_MUST_BE_ZERO;
3661     }
3662
3663     rq->id = ntohl(nfmr->id);
3664     rq->flags = flags;
3665     rq->out_port = ntohs(nfmr->out_port);
3666     rq->table_id = nfmr->table_id;
3667
3668     return nx_pull_match(msg, ntohs(nfmr->match_len), &rq->match, NULL, NULL);
3669 }
3670
3671 void
3672 ofputil_append_flow_monitor_request(
3673     const struct ofputil_flow_monitor_request *rq, struct ofpbuf *msg)
3674 {
3675     struct nx_flow_monitor_request *nfmr;
3676     size_t start_ofs;
3677     int match_len;
3678
3679     if (!msg->size) {
3680         ofpraw_put(OFPRAW_NXST_FLOW_MONITOR_REQUEST, OFP10_VERSION, msg);
3681     }
3682
3683     start_ofs = msg->size;
3684     ofpbuf_put_zeros(msg, sizeof *nfmr);
3685     match_len = nx_put_match(msg, &rq->match, htonll(0), htonll(0));
3686
3687     nfmr = ofpbuf_at_assert(msg, start_ofs, sizeof *nfmr);
3688     nfmr->id = htonl(rq->id);
3689     nfmr->flags = htons(rq->flags);
3690     nfmr->out_port = htons(rq->out_port);
3691     nfmr->match_len = htons(match_len);
3692     nfmr->table_id = rq->table_id;
3693 }
3694
3695 /* Converts an NXST_FLOW_MONITOR reply (also known as a flow update) in 'msg'
3696  * into an abstract ofputil_flow_update in 'update'.  The caller must have
3697  * initialized update->match to point to space allocated for a match.
3698  *
3699  * Uses 'ofpacts' to store the abstract OFPACT_* version of the update's
3700  * actions (except for NXFME_ABBREV, which never includes actions).  The caller
3701  * must initialize 'ofpacts' and retains ownership of it.  'update->ofpacts'
3702  * will point into the 'ofpacts' buffer.
3703  *
3704  * Multiple flow updates can be packed into a single OpenFlow message.  Calling
3705  * this function multiple times for a single 'msg' iterates through the
3706  * updates.  The caller must initially leave 'msg''s layer pointers null and
3707  * not modify them between calls.
3708  *
3709  * Returns 0 if successful, EOF if no updates were left in this 'msg',
3710  * otherwise an OFPERR_* value. */
3711 int
3712 ofputil_decode_flow_update(struct ofputil_flow_update *update,
3713                            struct ofpbuf *msg, struct ofpbuf *ofpacts)
3714 {
3715     struct nx_flow_update_header *nfuh;
3716     unsigned int length;
3717
3718     if (!msg->l2) {
3719         msg->l2 = msg->data;
3720         ofpraw_pull_assert(msg);
3721     }
3722
3723     if (!msg->size) {
3724         return EOF;
3725     }
3726
3727     if (msg->size < sizeof(struct nx_flow_update_header)) {
3728         goto bad_len;
3729     }
3730
3731     nfuh = msg->data;
3732     update->event = ntohs(nfuh->event);
3733     length = ntohs(nfuh->length);
3734     if (length > msg->size || length % 8) {
3735         goto bad_len;
3736     }
3737
3738     if (update->event == NXFME_ABBREV) {
3739         struct nx_flow_update_abbrev *nfua;
3740
3741         if (length != sizeof *nfua) {
3742             goto bad_len;
3743         }
3744
3745         nfua = ofpbuf_pull(msg, sizeof *nfua);
3746         update->xid = nfua->xid;
3747         return 0;
3748     } else if (update->event == NXFME_ADDED
3749                || update->event == NXFME_DELETED
3750                || update->event == NXFME_MODIFIED) {
3751         struct nx_flow_update_full *nfuf;
3752         unsigned int actions_len;
3753         unsigned int match_len;
3754         enum ofperr error;
3755
3756         if (length < sizeof *nfuf) {
3757             goto bad_len;
3758         }
3759
3760         nfuf = ofpbuf_pull(msg, sizeof *nfuf);
3761         match_len = ntohs(nfuf->match_len);
3762         if (sizeof *nfuf + match_len > length) {
3763             goto bad_len;
3764         }
3765
3766         update->reason = ntohs(nfuf->reason);
3767         update->idle_timeout = ntohs(nfuf->idle_timeout);
3768         update->hard_timeout = ntohs(nfuf->hard_timeout);
3769         update->table_id = nfuf->table_id;
3770         update->cookie = nfuf->cookie;
3771         update->priority = ntohs(nfuf->priority);
3772
3773         error = nx_pull_match(msg, match_len, update->match, NULL, NULL);
3774         if (error) {
3775             return error;
3776         }
3777
3778         actions_len = length - sizeof *nfuf - ROUND_UP(match_len, 8);
3779         error = ofpacts_pull_openflow10(msg, actions_len, ofpacts);
3780         if (error) {
3781             return error;
3782         }
3783
3784         update->ofpacts = ofpacts->data;
3785         update->ofpacts_len = ofpacts->size;
3786         return 0;
3787     } else {
3788         VLOG_WARN_RL(&bad_ofmsg_rl,
3789                      "NXST_FLOW_MONITOR reply has bad event %"PRIu16,
3790                      ntohs(nfuh->event));
3791         return OFPERR_NXBRC_FM_BAD_EVENT;
3792     }
3793
3794 bad_len:
3795     VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR reply has %zu "
3796                  "leftover bytes at end", msg->size);
3797     return OFPERR_OFPBRC_BAD_LEN;
3798 }
3799
3800 uint32_t
3801 ofputil_decode_flow_monitor_cancel(const struct ofp_header *oh)
3802 {
3803     const struct nx_flow_monitor_cancel *cancel = ofpmsg_body(oh);
3804
3805     return ntohl(cancel->id);
3806 }
3807
3808 struct ofpbuf *
3809 ofputil_encode_flow_monitor_cancel(uint32_t id)
3810 {
3811     struct nx_flow_monitor_cancel *nfmc;
3812     struct ofpbuf *msg;
3813
3814     msg = ofpraw_alloc(OFPRAW_NXT_FLOW_MONITOR_CANCEL, OFP10_VERSION, 0);
3815     nfmc = ofpbuf_put_uninit(msg, sizeof *nfmc);
3816     nfmc->id = htonl(id);
3817     return msg;
3818 }
3819
3820 void
3821 ofputil_start_flow_update(struct list *replies)
3822 {
3823     struct ofpbuf *msg;
3824
3825     msg = ofpraw_alloc_xid(OFPRAW_NXST_FLOW_MONITOR_REPLY, OFP10_VERSION,
3826                            htonl(0), 1024);
3827
3828     list_init(replies);
3829     list_push_back(replies, &msg->list_node);
3830 }
3831
3832 void
3833 ofputil_append_flow_update(const struct ofputil_flow_update *update,
3834                            struct list *replies)
3835 {
3836     struct nx_flow_update_header *nfuh;
3837     struct ofpbuf *msg;
3838     size_t start_ofs;
3839
3840     msg = ofpbuf_from_list(list_back(replies));
3841     start_ofs = msg->size;
3842
3843     if (update->event == NXFME_ABBREV) {
3844         struct nx_flow_update_abbrev *nfua;
3845
3846         nfua = ofpbuf_put_zeros(msg, sizeof *nfua);
3847         nfua->xid = update->xid;
3848     } else {
3849         struct nx_flow_update_full *nfuf;
3850         int match_len;
3851
3852         ofpbuf_put_zeros(msg, sizeof *nfuf);
3853         match_len = nx_put_match(msg, update->match, htonll(0), htonll(0));
3854         ofpacts_put_openflow10(update->ofpacts, update->ofpacts_len, msg);
3855
3856         nfuf = ofpbuf_at_assert(msg, start_ofs, sizeof *nfuf);
3857         nfuf->reason = htons(update->reason);
3858         nfuf->priority = htons(update->priority);
3859         nfuf->idle_timeout = htons(update->idle_timeout);
3860         nfuf->hard_timeout = htons(update->hard_timeout);
3861         nfuf->match_len = htons(match_len);
3862         nfuf->table_id = update->table_id;
3863         nfuf->cookie = update->cookie;
3864     }
3865
3866     nfuh = ofpbuf_at_assert(msg, start_ofs, sizeof *nfuh);
3867     nfuh->length = htons(msg->size - start_ofs);
3868     nfuh->event = htons(update->event);
3869
3870     ofpmp_postappend(replies, start_ofs);
3871 }
3872 \f
3873 struct ofpbuf *
3874 ofputil_encode_packet_out(const struct ofputil_packet_out *po,
3875                           enum ofputil_protocol protocol)
3876 {
3877     enum ofp_version ofp_version = ofputil_protocol_to_ofp_version(protocol);
3878     struct ofpbuf *msg;
3879     size_t size;
3880
3881     size = po->ofpacts_len;
3882     if (po->buffer_id == UINT32_MAX) {
3883         size += po->packet_len;
3884     }
3885
3886     switch (ofp_version) {
3887     case OFP10_VERSION: {
3888         struct ofp10_packet_out *opo;
3889         size_t actions_ofs;
3890
3891         msg = ofpraw_alloc(OFPRAW_OFPT10_PACKET_OUT, OFP10_VERSION, size);
3892         ofpbuf_put_zeros(msg, sizeof *opo);
3893         actions_ofs = msg->size;
3894         ofpacts_put_openflow10(po->ofpacts, po->ofpacts_len, msg);
3895
3896         opo = msg->l3;
3897         opo->buffer_id = htonl(po->buffer_id);
3898         opo->in_port = htons(po->in_port);
3899         opo->actions_len = htons(msg->size - actions_ofs);
3900         break;
3901     }
3902
3903     case OFP11_VERSION:
3904     case OFP12_VERSION:
3905     case OFP13_VERSION: {
3906         struct ofp11_packet_out *opo;
3907         size_t len;
3908
3909         msg = ofpraw_alloc(OFPRAW_OFPT11_PACKET_OUT, ofp_version, size);
3910         ofpbuf_put_zeros(msg, sizeof *opo);
3911         len = ofpacts_put_openflow11_actions(po->ofpacts, po->ofpacts_len, msg);
3912
3913         opo = msg->l3;
3914         opo->buffer_id = htonl(po->buffer_id);
3915         opo->in_port = ofputil_port_to_ofp11(po->in_port);
3916         opo->actions_len = htons(len);
3917         break;
3918     }
3919
3920     default:
3921         NOT_REACHED();
3922     }
3923
3924     if (po->buffer_id == UINT32_MAX) {
3925         ofpbuf_put(msg, po->packet, po->packet_len);
3926     }
3927
3928     ofpmsg_update_length(msg);
3929
3930     return msg;
3931 }
3932 \f
3933 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
3934 struct ofpbuf *
3935 make_echo_request(enum ofp_version ofp_version)
3936 {
3937     return ofpraw_alloc_xid(OFPRAW_OFPT_ECHO_REQUEST, ofp_version,
3938                             htonl(0), 0);
3939 }
3940
3941 /* Creates and returns an OFPT_ECHO_REPLY message matching the
3942  * OFPT_ECHO_REQUEST message in 'rq'. */
3943 struct ofpbuf *
3944 make_echo_reply(const struct ofp_header *rq)
3945 {
3946     struct ofpbuf rq_buf;
3947     struct ofpbuf *reply;
3948
3949     ofpbuf_use_const(&rq_buf, rq, ntohs(rq->length));
3950     ofpraw_pull_assert(&rq_buf);
3951
3952     reply = ofpraw_alloc_reply(OFPRAW_OFPT_ECHO_REPLY, rq, rq_buf.size);
3953     ofpbuf_put(reply, rq_buf.data, rq_buf.size);
3954     return reply;
3955 }
3956
3957 struct ofpbuf *
3958 ofputil_encode_barrier_request(enum ofp_version ofp_version)
3959 {
3960     enum ofpraw type;
3961
3962     switch (ofp_version) {
3963     case OFP13_VERSION:
3964     case OFP12_VERSION:
3965     case OFP11_VERSION:
3966         type = OFPRAW_OFPT11_BARRIER_REQUEST;
3967         break;
3968
3969     case OFP10_VERSION:
3970         type = OFPRAW_OFPT10_BARRIER_REQUEST;
3971         break;
3972
3973     default:
3974         NOT_REACHED();
3975     }
3976
3977     return ofpraw_alloc(type, ofp_version, 0);
3978 }
3979
3980 const char *
3981 ofputil_frag_handling_to_string(enum ofp_config_flags flags)
3982 {
3983     switch (flags & OFPC_FRAG_MASK) {
3984     case OFPC_FRAG_NORMAL:   return "normal";
3985     case OFPC_FRAG_DROP:     return "drop";
3986     case OFPC_FRAG_REASM:    return "reassemble";
3987     case OFPC_FRAG_NX_MATCH: return "nx-match";
3988     }
3989
3990     NOT_REACHED();
3991 }
3992
3993 bool
3994 ofputil_frag_handling_from_string(const char *s, enum ofp_config_flags *flags)
3995 {
3996     if (!strcasecmp(s, "normal")) {
3997         *flags = OFPC_FRAG_NORMAL;
3998     } else if (!strcasecmp(s, "drop")) {
3999         *flags = OFPC_FRAG_DROP;
4000     } else if (!strcasecmp(s, "reassemble")) {
4001         *flags = OFPC_FRAG_REASM;
4002     } else if (!strcasecmp(s, "nx-match")) {
4003         *flags = OFPC_FRAG_NX_MATCH;
4004     } else {
4005         return false;
4006     }
4007     return true;
4008 }
4009
4010 /* Converts the OpenFlow 1.1+ port number 'ofp11_port' into an OpenFlow 1.0
4011  * port number and stores the latter in '*ofp10_port', for the purpose of
4012  * decoding OpenFlow 1.1+ protocol messages.  Returns 0 if successful,
4013  * otherwise an OFPERR_* number.
4014  *
4015  * See the definition of OFP11_MAX for an explanation of the mapping. */
4016 enum ofperr
4017 ofputil_port_from_ofp11(ovs_be32 ofp11_port, uint16_t *ofp10_port)
4018 {
4019     uint32_t ofp11_port_h = ntohl(ofp11_port);
4020
4021     if (ofp11_port_h < OFPP_MAX) {
4022         *ofp10_port = ofp11_port_h;
4023         return 0;
4024     } else if (ofp11_port_h >= OFPP11_MAX) {
4025         *ofp10_port = ofp11_port_h - OFPP11_OFFSET;
4026         return 0;
4027     } else {
4028         VLOG_WARN_RL(&bad_ofmsg_rl, "port %"PRIu32" is outside the supported "
4029                      "range 0 through %d or 0x%"PRIx32" through 0x%"PRIx32,
4030                      ofp11_port_h, OFPP_MAX - 1,
4031                      (uint32_t) OFPP11_MAX, UINT32_MAX);
4032         return OFPERR_OFPBAC_BAD_OUT_PORT;
4033     }
4034 }
4035
4036 /* Returns the OpenFlow 1.1+ port number equivalent to the OpenFlow 1.0 port
4037  * number 'ofp10_port', for encoding OpenFlow 1.1+ protocol messages.
4038  *
4039  * See the definition of OFP11_MAX for an explanation of the mapping. */
4040 ovs_be32
4041 ofputil_port_to_ofp11(uint16_t ofp10_port)
4042 {
4043     return htonl(ofp10_port < OFPP_MAX
4044                  ? ofp10_port
4045                  : ofp10_port + OFPP11_OFFSET);
4046 }
4047
4048 /* Checks that 'port' is a valid output port for the OFPAT10_OUTPUT action, given
4049  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
4050  * 'port' is valid, otherwise an OpenFlow return code. */
4051 enum ofperr
4052 ofputil_check_output_port(uint16_t port, int max_ports)
4053 {
4054     switch (port) {
4055     case OFPP_IN_PORT:
4056     case OFPP_TABLE:
4057     case OFPP_NORMAL:
4058     case OFPP_FLOOD:
4059     case OFPP_ALL:
4060     case OFPP_CONTROLLER:
4061     case OFPP_NONE:
4062     case OFPP_LOCAL:
4063         return 0;
4064
4065     default:
4066         if (port < max_ports) {
4067             return 0;
4068         }
4069         return OFPERR_OFPBAC_BAD_OUT_PORT;
4070     }
4071 }
4072
4073 #define OFPUTIL_NAMED_PORTS                     \
4074         OFPUTIL_NAMED_PORT(IN_PORT)             \
4075         OFPUTIL_NAMED_PORT(TABLE)               \
4076         OFPUTIL_NAMED_PORT(NORMAL)              \
4077         OFPUTIL_NAMED_PORT(FLOOD)               \
4078         OFPUTIL_NAMED_PORT(ALL)                 \
4079         OFPUTIL_NAMED_PORT(CONTROLLER)          \
4080         OFPUTIL_NAMED_PORT(LOCAL)               \
4081         OFPUTIL_NAMED_PORT(ANY)
4082
4083 /* For backwards compatibility, so that "none" is recognized as OFPP_ANY */
4084 #define OFPUTIL_NAMED_PORTS_WITH_NONE           \
4085         OFPUTIL_NAMED_PORTS                     \
4086         OFPUTIL_NAMED_PORT(NONE)
4087
4088 /* Stores the port number represented by 's' into '*portp'.  's' may be an
4089  * integer or, for reserved ports, the standard OpenFlow name for the port
4090  * (e.g. "LOCAL").
4091  *
4092  * Returns true if successful, false if 's' is not a valid OpenFlow port number
4093  * or name.  The caller should issue an error message in this case, because
4094  * this function usually does not.  (This gives the caller an opportunity to
4095  * look up the port name another way, e.g. by contacting the switch and listing
4096  * the names of all its ports).
4097  *
4098  * This function accepts OpenFlow 1.0 port numbers.  It also accepts a subset
4099  * of OpenFlow 1.1+ port numbers, mapping those port numbers into the 16-bit
4100  * range as described in include/openflow/openflow-1.1.h. */
4101 bool
4102 ofputil_port_from_string(const char *s, uint16_t *portp)
4103 {
4104     unsigned int port32;
4105
4106     *portp = 0;
4107     if (str_to_uint(s, 10, &port32)) {
4108         if (port32 < OFPP_MAX) {
4109             *portp = port32;
4110             return true;
4111         } else if (port32 < OFPP_FIRST_RESV) {
4112             VLOG_WARN("port %u is a reserved OF1.0 port number that will "
4113                       "be translated to %u when talking to an OF1.1 or "
4114                       "later controller", port32, port32 + OFPP11_OFFSET);
4115             *portp = port32;
4116             return true;
4117         } else if (port32 <= OFPP_LAST_RESV) {
4118             struct ds s;
4119
4120             ds_init(&s);
4121             ofputil_format_port(port32, &s);
4122             VLOG_WARN_ONCE("referring to port %s as %u is deprecated for "
4123                            "compatibility with future versions of OpenFlow",
4124                            ds_cstr(&s), port32);
4125             ds_destroy(&s);
4126
4127             *portp = port32;
4128             return true;
4129         } else if (port32 < OFPP11_MAX) {
4130             VLOG_WARN("port %u is outside the supported range 0 through "
4131                       "%"PRIx16" or 0x%x through 0x%"PRIx32, port32,
4132                       UINT16_MAX, (unsigned int) OFPP11_MAX, UINT32_MAX);
4133             return false;
4134         } else {
4135             *portp = port32 - OFPP11_OFFSET;
4136             return true;
4137         }
4138     } else {
4139         struct pair {
4140             const char *name;
4141             uint16_t value;
4142         };
4143         static const struct pair pairs[] = {
4144 #define OFPUTIL_NAMED_PORT(NAME) {#NAME, OFPP_##NAME},
4145             OFPUTIL_NAMED_PORTS_WITH_NONE
4146 #undef OFPUTIL_NAMED_PORT
4147         };
4148         const struct pair *p;
4149
4150         for (p = pairs; p < &pairs[ARRAY_SIZE(pairs)]; p++) {
4151             if (!strcasecmp(s, p->name)) {
4152                 *portp = p->value;
4153                 return true;
4154             }
4155         }
4156         return false;
4157     }
4158 }
4159
4160 /* Appends to 's' a string representation of the OpenFlow port number 'port'.
4161  * Most ports' string representation is just the port number, but for special
4162  * ports, e.g. OFPP_LOCAL, it is the name, e.g. "LOCAL". */
4163 void
4164 ofputil_format_port(uint16_t port, struct ds *s)
4165 {
4166     const char *name;
4167
4168     switch (port) {
4169 #define OFPUTIL_NAMED_PORT(NAME) case OFPP_##NAME: name = #NAME; break;
4170         OFPUTIL_NAMED_PORTS
4171 #undef OFPUTIL_NAMED_PORT
4172
4173     default:
4174         ds_put_format(s, "%"PRIu16, port);
4175         return;
4176     }
4177     ds_put_cstr(s, name);
4178 }
4179
4180 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
4181  * 'ofp_version', tries to pull the first element from the array.  If
4182  * successful, initializes '*pp' with an abstract representation of the
4183  * port and returns 0.  If no ports remain to be decoded, returns EOF.
4184  * On an error, returns a positive OFPERR_* value. */
4185 int
4186 ofputil_pull_phy_port(enum ofp_version ofp_version, struct ofpbuf *b,
4187                       struct ofputil_phy_port *pp)
4188 {
4189     switch (ofp_version) {
4190     case OFP10_VERSION: {
4191         const struct ofp10_phy_port *opp = ofpbuf_try_pull(b, sizeof *opp);
4192         return opp ? ofputil_decode_ofp10_phy_port(pp, opp) : EOF;
4193     }
4194     case OFP11_VERSION:
4195     case OFP12_VERSION:
4196     case OFP13_VERSION: {
4197         const struct ofp11_port *op = ofpbuf_try_pull(b, sizeof *op);
4198         return op ? ofputil_decode_ofp11_port(pp, op) : EOF;
4199     }
4200     default:
4201         NOT_REACHED();
4202     }
4203 }
4204
4205 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
4206  * 'ofp_version', returns the number of elements. */
4207 size_t ofputil_count_phy_ports(uint8_t ofp_version, struct ofpbuf *b)
4208 {
4209     return b->size / ofputil_get_phy_port_size(ofp_version);
4210 }
4211
4212 /* Returns the 'enum ofputil_action_code' corresponding to 'name' (e.g. if
4213  * 'name' is "output" then the return value is OFPUTIL_OFPAT10_OUTPUT), or -1 if
4214  * 'name' is not the name of any action.
4215  *
4216  * ofp-util.def lists the mapping from names to action. */
4217 int
4218 ofputil_action_code_from_name(const char *name)
4219 {
4220     static const char *names[OFPUTIL_N_ACTIONS] = {
4221         NULL,
4222 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)             NAME,
4223 #define OFPAT11_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) NAME,
4224 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)   NAME,
4225 #include "ofp-util.def"
4226     };
4227
4228     const char **p;
4229
4230     for (p = names; p < &names[ARRAY_SIZE(names)]; p++) {
4231         if (*p && !strcasecmp(name, *p)) {
4232             return p - names;
4233         }
4234     }
4235     return -1;
4236 }
4237
4238 /* Appends an action of the type specified by 'code' to 'buf' and returns the
4239  * action.  Initializes the parts of 'action' that identify it as having type
4240  * <ENUM> and length 'sizeof *action' and zeros the rest.  For actions that
4241  * have variable length, the length used and cleared is that of struct
4242  * <STRUCT>.  */
4243 void *
4244 ofputil_put_action(enum ofputil_action_code code, struct ofpbuf *buf)
4245 {
4246     switch (code) {
4247     case OFPUTIL_ACTION_INVALID:
4248         NOT_REACHED();
4249
4250 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                  \
4251     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
4252 #define OFPAT11_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)      \
4253     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
4254 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)        \
4255     case OFPUTIL_##ENUM: return ofputil_put_##ENUM(buf);
4256 #include "ofp-util.def"
4257     }
4258     NOT_REACHED();
4259 }
4260
4261 #define OFPAT10_ACTION(ENUM, STRUCT, NAME)                        \
4262     void                                                        \
4263     ofputil_init_##ENUM(struct STRUCT *s)                       \
4264     {                                                           \
4265         memset(s, 0, sizeof *s);                                \
4266         s->type = htons(ENUM);                                  \
4267         s->len = htons(sizeof *s);                              \
4268     }                                                           \
4269                                                                 \
4270     struct STRUCT *                                             \
4271     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
4272     {                                                           \
4273         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
4274         ofputil_init_##ENUM(s);                                 \
4275         return s;                                               \
4276     }
4277 #define OFPAT11_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) \
4278     OFPAT10_ACTION(ENUM, STRUCT, NAME)
4279 #define NXAST_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME)            \
4280     void                                                        \
4281     ofputil_init_##ENUM(struct STRUCT *s)                       \
4282     {                                                           \
4283         memset(s, 0, sizeof *s);                                \
4284         s->type = htons(OFPAT10_VENDOR);                        \
4285         s->len = htons(sizeof *s);                              \
4286         s->vendor = htonl(NX_VENDOR_ID);                        \
4287         s->subtype = htons(ENUM);                               \
4288     }                                                           \
4289                                                                 \
4290     struct STRUCT *                                             \
4291     ofputil_put_##ENUM(struct ofpbuf *buf)                      \
4292     {                                                           \
4293         struct STRUCT *s = ofpbuf_put_uninit(buf, sizeof *s);   \
4294         ofputil_init_##ENUM(s);                                 \
4295         return s;                                               \
4296     }
4297 #include "ofp-util.def"
4298
4299 static void
4300 ofputil_normalize_match__(struct match *match, bool may_log)
4301 {
4302     enum {
4303         MAY_NW_ADDR     = 1 << 0, /* nw_src, nw_dst */
4304         MAY_TP_ADDR     = 1 << 1, /* tp_src, tp_dst */
4305         MAY_NW_PROTO    = 1 << 2, /* nw_proto */
4306         MAY_IPVx        = 1 << 3, /* tos, frag, ttl */
4307         MAY_ARP_SHA     = 1 << 4, /* arp_sha */
4308         MAY_ARP_THA     = 1 << 5, /* arp_tha */
4309         MAY_IPV6        = 1 << 6, /* ipv6_src, ipv6_dst, ipv6_label */
4310         MAY_ND_TARGET   = 1 << 7  /* nd_target */
4311     } may_match;
4312
4313     struct flow_wildcards wc;
4314
4315     /* Figure out what fields may be matched. */
4316     if (match->flow.dl_type == htons(ETH_TYPE_IP)) {
4317         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_NW_ADDR;
4318         if (match->flow.nw_proto == IPPROTO_TCP ||
4319             match->flow.nw_proto == IPPROTO_UDP ||
4320             match->flow.nw_proto == IPPROTO_ICMP) {
4321             may_match |= MAY_TP_ADDR;
4322         }
4323     } else if (match->flow.dl_type == htons(ETH_TYPE_IPV6)) {
4324         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_IPV6;
4325         if (match->flow.nw_proto == IPPROTO_TCP ||
4326             match->flow.nw_proto == IPPROTO_UDP) {
4327             may_match |= MAY_TP_ADDR;
4328         } else if (match->flow.nw_proto == IPPROTO_ICMPV6) {
4329             may_match |= MAY_TP_ADDR;
4330             if (match->flow.tp_src == htons(ND_NEIGHBOR_SOLICIT)) {
4331                 may_match |= MAY_ND_TARGET | MAY_ARP_SHA;
4332             } else if (match->flow.tp_src == htons(ND_NEIGHBOR_ADVERT)) {
4333                 may_match |= MAY_ND_TARGET | MAY_ARP_THA;
4334             }
4335         }
4336     } else if (match->flow.dl_type == htons(ETH_TYPE_ARP) ||
4337                match->flow.dl_type == htons(ETH_TYPE_RARP)) {
4338         may_match = MAY_NW_PROTO | MAY_NW_ADDR | MAY_ARP_SHA | MAY_ARP_THA;
4339     } else {
4340         may_match = 0;
4341     }
4342
4343     /* Clear the fields that may not be matched. */
4344     wc = match->wc;
4345     if (!(may_match & MAY_NW_ADDR)) {
4346         wc.masks.nw_src = wc.masks.nw_dst = htonl(0);
4347     }
4348     if (!(may_match & MAY_TP_ADDR)) {
4349         wc.masks.tp_src = wc.masks.tp_dst = htons(0);
4350     }
4351     if (!(may_match & MAY_NW_PROTO)) {
4352         wc.masks.nw_proto = 0;
4353     }
4354     if (!(may_match & MAY_IPVx)) {
4355         wc.masks.nw_tos = 0;
4356         wc.masks.nw_ttl = 0;
4357     }
4358     if (!(may_match & MAY_ARP_SHA)) {
4359         memset(wc.masks.arp_sha, 0, ETH_ADDR_LEN);
4360     }
4361     if (!(may_match & MAY_ARP_THA)) {
4362         memset(wc.masks.arp_tha, 0, ETH_ADDR_LEN);
4363     }
4364     if (!(may_match & MAY_IPV6)) {
4365         wc.masks.ipv6_src = wc.masks.ipv6_dst = in6addr_any;
4366         wc.masks.ipv6_label = htonl(0);
4367     }
4368     if (!(may_match & MAY_ND_TARGET)) {
4369         wc.masks.nd_target = in6addr_any;
4370     }
4371
4372     /* Log any changes. */
4373     if (!flow_wildcards_equal(&wc, &match->wc)) {
4374         bool log = may_log && !VLOG_DROP_INFO(&bad_ofmsg_rl);
4375         char *pre = log ? match_to_string(match, OFP_DEFAULT_PRIORITY) : NULL;
4376
4377         match->wc = wc;
4378         match_zero_wildcarded_fields(match);
4379
4380         if (log) {
4381             char *post = match_to_string(match, OFP_DEFAULT_PRIORITY);
4382             VLOG_INFO("normalization changed ofp_match, details:");
4383             VLOG_INFO(" pre: %s", pre);
4384             VLOG_INFO("post: %s", post);
4385             free(pre);
4386             free(post);
4387         }
4388     }
4389 }
4390
4391 /* "Normalizes" the wildcards in 'match'.  That means:
4392  *
4393  *    1. If the type of level N is known, then only the valid fields for that
4394  *       level may be specified.  For example, ARP does not have a TOS field,
4395  *       so nw_tos must be wildcarded if 'match' specifies an ARP flow.
4396  *       Similarly, IPv4 does not have any IPv6 addresses, so ipv6_src and
4397  *       ipv6_dst (and other fields) must be wildcarded if 'match' specifies an
4398  *       IPv4 flow.
4399  *
4400  *    2. If the type of level N is not known (or not understood by Open
4401  *       vSwitch), then no fields at all for that level may be specified.  For
4402  *       example, Open vSwitch does not understand SCTP, an L4 protocol, so the
4403  *       L4 fields tp_src and tp_dst must be wildcarded if 'match' specifies an
4404  *       SCTP flow.
4405  *
4406  * If this function changes 'match', it logs a rate-limited informational
4407  * message. */
4408 void
4409 ofputil_normalize_match(struct match *match)
4410 {
4411     ofputil_normalize_match__(match, true);
4412 }
4413
4414 /* Same as ofputil_normalize_match() without the logging.  Thus, this function
4415  * is suitable for a program's internal use, whereas ofputil_normalize_match()
4416  * sense for use on flows received from elsewhere (so that a bug in the program
4417  * that sent them can be reported and corrected). */
4418 void
4419 ofputil_normalize_match_quiet(struct match *match)
4420 {
4421     ofputil_normalize_match__(match, false);
4422 }
4423
4424 /* Parses a key or a key-value pair from '*stringp'.
4425  *
4426  * On success: Stores the key into '*keyp'.  Stores the value, if present, into
4427  * '*valuep', otherwise an empty string.  Advances '*stringp' past the end of
4428  * the key-value pair, preparing it for another call.  '*keyp' and '*valuep'
4429  * are substrings of '*stringp' created by replacing some of its bytes by null
4430  * terminators.  Returns true.
4431  *
4432  * If '*stringp' is just white space or commas, sets '*keyp' and '*valuep' to
4433  * NULL and returns false. */
4434 bool
4435 ofputil_parse_key_value(char **stringp, char **keyp, char **valuep)
4436 {
4437     char *pos, *key, *value;
4438     size_t key_len;
4439
4440     pos = *stringp;
4441     pos += strspn(pos, ", \t\r\n");
4442     if (*pos == '\0') {
4443         *keyp = *valuep = NULL;
4444         return false;
4445     }
4446
4447     key = pos;
4448     key_len = strcspn(pos, ":=(, \t\r\n");
4449     if (key[key_len] == ':' || key[key_len] == '=') {
4450         /* The value can be separated by a colon. */
4451         size_t value_len;
4452
4453         value = key + key_len + 1;
4454         value_len = strcspn(value, ", \t\r\n");
4455         pos = value + value_len + (value[value_len] != '\0');
4456         value[value_len] = '\0';
4457     } else if (key[key_len] == '(') {
4458         /* The value can be surrounded by balanced parentheses.  The outermost
4459          * set of parentheses is removed. */
4460         int level = 1;
4461         size_t value_len;
4462
4463         value = key + key_len + 1;
4464         for (value_len = 0; level > 0; value_len++) {
4465             switch (value[value_len]) {
4466             case '\0':
4467                 level = 0;
4468                 break;
4469
4470             case '(':
4471                 level++;
4472                 break;
4473
4474             case ')':
4475                 level--;
4476                 break;
4477             }
4478         }
4479         value[value_len - 1] = '\0';
4480         pos = value + value_len;
4481     } else {
4482         /* There might be no value at all. */
4483         value = key + key_len;  /* Will become the empty string below. */
4484         pos = key + key_len + (key[key_len] != '\0');
4485     }
4486     key[key_len] = '\0';
4487
4488     *stringp = pos;
4489     *keyp = key;
4490     *valuep = value;
4491     return true;
4492 }
4493
4494 /* Encode a dump ports request for 'port', the encoded message
4495  * will be for Open Flow version 'ofp_version'. Returns message
4496  * as a struct ofpbuf. Returns encoded message on success, NULL on error */
4497 struct ofpbuf *
4498 ofputil_encode_dump_ports_request(enum ofp_version ofp_version, int16_t port)
4499 {
4500     struct ofpbuf *request;
4501
4502     switch (ofp_version) {
4503     case OFP10_VERSION: {
4504         struct ofp10_port_stats_request *req;
4505         request = ofpraw_alloc(OFPRAW_OFPST10_PORT_REQUEST, ofp_version, 0);
4506         req = ofpbuf_put_zeros(request, sizeof *req);
4507         req->port_no = htons(port);
4508         break;
4509     }
4510     case OFP11_VERSION:
4511     case OFP12_VERSION:
4512     case OFP13_VERSION: {
4513         struct ofp11_port_stats_request *req;
4514         request = ofpraw_alloc(OFPRAW_OFPST11_PORT_REQUEST, ofp_version, 0);
4515         req = ofpbuf_put_zeros(request, sizeof *req);
4516         req->port_no = ofputil_port_to_ofp11(port);
4517         break;
4518     }
4519     default:
4520         NOT_REACHED();
4521     }
4522
4523     return request;
4524 }
4525
4526 static void
4527 ofputil_port_stats_to_ofp10(const struct ofputil_port_stats *ops,
4528                             struct ofp10_port_stats *ps10)
4529 {
4530     ps10->port_no = htons(ops->port_no);
4531     memset(ps10->pad, 0, sizeof ps10->pad);
4532     put_32aligned_be64(&ps10->rx_packets, htonll(ops->stats.rx_packets));
4533     put_32aligned_be64(&ps10->tx_packets, htonll(ops->stats.tx_packets));
4534     put_32aligned_be64(&ps10->rx_bytes, htonll(ops->stats.rx_bytes));
4535     put_32aligned_be64(&ps10->tx_bytes, htonll(ops->stats.tx_bytes));
4536     put_32aligned_be64(&ps10->rx_dropped, htonll(ops->stats.rx_dropped));
4537     put_32aligned_be64(&ps10->tx_dropped, htonll(ops->stats.tx_dropped));
4538     put_32aligned_be64(&ps10->rx_errors, htonll(ops->stats.rx_errors));
4539     put_32aligned_be64(&ps10->tx_errors, htonll(ops->stats.tx_errors));
4540     put_32aligned_be64(&ps10->rx_frame_err, htonll(ops->stats.rx_frame_errors));
4541     put_32aligned_be64(&ps10->rx_over_err, htonll(ops->stats.rx_over_errors));
4542     put_32aligned_be64(&ps10->rx_crc_err, htonll(ops->stats.rx_crc_errors));
4543     put_32aligned_be64(&ps10->collisions, htonll(ops->stats.collisions));
4544 }
4545
4546 static void
4547 ofputil_port_stats_to_ofp11(const struct ofputil_port_stats *ops,
4548                             struct ofp11_port_stats *ps11)
4549 {
4550     ps11->port_no = ofputil_port_to_ofp11(ops->port_no);
4551     memset(ps11->pad, 0, sizeof ps11->pad);
4552     ps11->rx_packets = htonll(ops->stats.rx_packets);
4553     ps11->tx_packets = htonll(ops->stats.tx_packets);
4554     ps11->rx_bytes = htonll(ops->stats.rx_bytes);
4555     ps11->tx_bytes = htonll(ops->stats.tx_bytes);
4556     ps11->rx_dropped = htonll(ops->stats.rx_dropped);
4557     ps11->tx_dropped = htonll(ops->stats.tx_dropped);
4558     ps11->rx_errors = htonll(ops->stats.rx_errors);
4559     ps11->tx_errors = htonll(ops->stats.tx_errors);
4560     ps11->rx_frame_err = htonll(ops->stats.rx_frame_errors);
4561     ps11->rx_over_err = htonll(ops->stats.rx_over_errors);
4562     ps11->rx_crc_err = htonll(ops->stats.rx_crc_errors);
4563     ps11->collisions = htonll(ops->stats.collisions);
4564 }
4565
4566 static void
4567 ofputil_port_stats_to_ofp13(const struct ofputil_port_stats *ops,
4568                             struct ofp13_port_stats *ps13)
4569 {
4570     ofputil_port_stats_to_ofp11(ops, &ps13->ps);
4571
4572     /* OF 1.3 adds duration fields */
4573     /* FIXME: Need to implement port alive duration (sec + nsec) */
4574     ps13->duration_sec = htonl(~0);
4575     ps13->duration_nsec = htonl(~0);
4576 }
4577
4578
4579 /* Encode a ports stat for 'ops' and append it to 'replies'. */
4580 void
4581 ofputil_append_port_stat(struct list *replies,
4582                          const struct ofputil_port_stats *ops)
4583 {
4584     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
4585     struct ofp_header *oh = msg->data;
4586
4587     switch ((enum ofp_version)oh->version) {
4588     case OFP13_VERSION: {
4589         struct ofp13_port_stats *reply = ofpmp_append(replies, sizeof *reply);
4590         ofputil_port_stats_to_ofp13(ops, reply);
4591         break;
4592     }
4593     case OFP12_VERSION:
4594     case OFP11_VERSION: {
4595         struct ofp11_port_stats *reply = ofpmp_append(replies, sizeof *reply);
4596         ofputil_port_stats_to_ofp11(ops, reply);
4597         break;
4598     }
4599
4600     case OFP10_VERSION: {
4601         struct ofp10_port_stats *reply = ofpmp_append(replies, sizeof *reply);
4602         ofputil_port_stats_to_ofp10(ops, reply);
4603         break;
4604     }
4605
4606     default:
4607         NOT_REACHED();
4608     }
4609 }
4610
4611 static enum ofperr
4612 ofputil_port_stats_from_ofp10(struct ofputil_port_stats *ops,
4613                               const struct ofp10_port_stats *ps10)
4614 {
4615     memset(ops, 0, sizeof *ops);
4616
4617     ops->port_no = ntohs(ps10->port_no);
4618     ops->stats.rx_packets = ntohll(get_32aligned_be64(&ps10->rx_packets));
4619     ops->stats.tx_packets = ntohll(get_32aligned_be64(&ps10->tx_packets));
4620     ops->stats.rx_bytes = ntohll(get_32aligned_be64(&ps10->rx_bytes));
4621     ops->stats.tx_bytes = ntohll(get_32aligned_be64(&ps10->tx_bytes));
4622     ops->stats.rx_dropped = ntohll(get_32aligned_be64(&ps10->rx_dropped));
4623     ops->stats.tx_dropped = ntohll(get_32aligned_be64(&ps10->tx_dropped));
4624     ops->stats.rx_errors = ntohll(get_32aligned_be64(&ps10->rx_errors));
4625     ops->stats.tx_errors = ntohll(get_32aligned_be64(&ps10->tx_errors));
4626     ops->stats.rx_frame_errors =
4627         ntohll(get_32aligned_be64(&ps10->rx_frame_err));
4628     ops->stats.rx_over_errors = ntohll(get_32aligned_be64(&ps10->rx_over_err));
4629     ops->stats.rx_crc_errors = ntohll(get_32aligned_be64(&ps10->rx_crc_err));
4630     ops->stats.collisions = ntohll(get_32aligned_be64(&ps10->collisions));
4631
4632     return 0;
4633 }
4634
4635 static enum ofperr
4636 ofputil_port_stats_from_ofp11(struct ofputil_port_stats *ops,
4637                               const struct ofp11_port_stats *ps11)
4638 {
4639     enum ofperr error;
4640
4641     memset(ops, 0, sizeof *ops);
4642     error = ofputil_port_from_ofp11(ps11->port_no, &ops->port_no);
4643     if (error) {
4644         return error;
4645     }
4646
4647     ops->stats.rx_packets = ntohll(ps11->rx_packets);
4648     ops->stats.tx_packets = ntohll(ps11->tx_packets);
4649     ops->stats.rx_bytes = ntohll(ps11->rx_bytes);
4650     ops->stats.tx_bytes = ntohll(ps11->tx_bytes);
4651     ops->stats.rx_dropped = ntohll(ps11->rx_dropped);
4652     ops->stats.tx_dropped = ntohll(ps11->tx_dropped);
4653     ops->stats.rx_errors = ntohll(ps11->rx_errors);
4654     ops->stats.tx_errors = ntohll(ps11->tx_errors);
4655     ops->stats.rx_frame_errors = ntohll(ps11->rx_frame_err);
4656     ops->stats.rx_over_errors = ntohll(ps11->rx_over_err);
4657     ops->stats.rx_crc_errors = ntohll(ps11->rx_crc_err);
4658     ops->stats.collisions = ntohll(ps11->collisions);
4659
4660     return 0;
4661 }
4662
4663 static enum ofperr
4664 ofputil_port_stats_from_ofp13(struct ofputil_port_stats *ops,
4665                               const struct ofp13_port_stats *ps13)
4666 {
4667     enum ofperr error =
4668         ofputil_port_stats_from_ofp11(ops, &ps13->ps);
4669     if (!error) {
4670         /* FIXME: Get ps13->duration_sec and ps13->duration_nsec,
4671          * Add to netdev_stats? */
4672     }
4673
4674     return error;
4675 }
4676
4677
4678 /* Returns the number of port stats elements in OFPTYPE_PORT_STATS_REPLY
4679  * message 'oh'. */
4680 size_t
4681 ofputil_count_port_stats(const struct ofp_header *oh)
4682 {
4683     struct ofpbuf b;
4684
4685     ofpbuf_use_const(&b, oh, ntohs(oh->length));
4686     ofpraw_pull_assert(&b);
4687
4688     BUILD_ASSERT(sizeof(struct ofp10_port_stats) ==
4689                  sizeof(struct ofp11_port_stats));
4690     return b.size / sizeof(struct ofp10_port_stats);
4691 }
4692
4693 /* Converts an OFPST_PORT_STATS reply in 'msg' into an abstract
4694  * ofputil_port_stats in 'ps'.
4695  *
4696  * Multiple OFPST_PORT_STATS replies can be packed into a single OpenFlow
4697  * message.  Calling this function multiple times for a single 'msg' iterates
4698  * through the replies.  The caller must initially leave 'msg''s layer pointers
4699  * null and not modify them between calls.
4700  *
4701  * Returns 0 if successful, EOF if no replies were left in this 'msg',
4702  * otherwise a positive errno value. */
4703 int
4704 ofputil_decode_port_stats(struct ofputil_port_stats *ps, struct ofpbuf *msg)
4705 {
4706     enum ofperr error;
4707     enum ofpraw raw;
4708
4709     error = (msg->l2
4710              ? ofpraw_decode(&raw, msg->l2)
4711              : ofpraw_pull(&raw, msg));
4712     if (error) {
4713         return error;
4714     }
4715
4716     if (!msg->size) {
4717         return EOF;
4718     } else if (raw == OFPRAW_OFPST13_PORT_REPLY) {
4719         const struct ofp13_port_stats *ps13;
4720
4721         ps13 = ofpbuf_try_pull(msg, sizeof *ps13);
4722         if (!ps13) {
4723             goto bad_len;
4724         }
4725         return ofputil_port_stats_from_ofp13(ps, ps13);
4726     } else if (raw == OFPRAW_OFPST11_PORT_REPLY) {
4727         const struct ofp11_port_stats *ps11;
4728
4729         ps11 = ofpbuf_try_pull(msg, sizeof *ps11);
4730         if (!ps11) {
4731             goto bad_len;
4732         }
4733         return ofputil_port_stats_from_ofp11(ps, ps11);
4734     } else if (raw == OFPRAW_OFPST10_PORT_REPLY) {
4735         const struct ofp10_port_stats *ps10;
4736
4737         ps10 = ofpbuf_try_pull(msg, sizeof *ps10);
4738         if (!ps10) {
4739             goto bad_len;
4740         }
4741         return ofputil_port_stats_from_ofp10(ps, ps10);
4742     } else {
4743         NOT_REACHED();
4744     }
4745
4746  bad_len:
4747     VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_PORT reply has %zu leftover "
4748                  "bytes at end", msg->size);
4749     return OFPERR_OFPBRC_BAD_LEN;
4750 }
4751
4752 /* Parse a port status request message into a 16 bit OpenFlow 1.0
4753  * port number and stores the latter in '*ofp10_port'.
4754  * Returns 0 if successful, otherwise an OFPERR_* number. */
4755 enum ofperr
4756 ofputil_decode_port_stats_request(const struct ofp_header *request,
4757                                   uint16_t *ofp10_port)
4758 {
4759     switch ((enum ofp_version)request->version) {
4760     case OFP13_VERSION:
4761     case OFP12_VERSION:
4762     case OFP11_VERSION: {
4763         const struct ofp11_port_stats_request *psr11 = ofpmsg_body(request);
4764         return ofputil_port_from_ofp11(psr11->port_no, ofp10_port);
4765     }
4766
4767     case OFP10_VERSION: {
4768         const struct ofp10_port_stats_request *psr10 = ofpmsg_body(request);
4769         *ofp10_port = ntohs(psr10->port_no);
4770         return 0;
4771     }
4772
4773     default:
4774         NOT_REACHED();
4775     }
4776 }
4777
4778 /* Parse a queue status request message into 'oqsr'.
4779  * Returns 0 if successful, otherwise an OFPERR_* number. */
4780 enum ofperr
4781 ofputil_decode_queue_stats_request(const struct ofp_header *request,
4782                                    struct ofputil_queue_stats_request *oqsr)
4783 {
4784     switch ((enum ofp_version)request->version) {
4785     case OFP13_VERSION:
4786     case OFP12_VERSION:
4787     case OFP11_VERSION: {
4788         const struct ofp11_queue_stats_request *qsr11 = ofpmsg_body(request);
4789         oqsr->queue_id = ntohl(qsr11->queue_id);
4790         return ofputil_port_from_ofp11(qsr11->port_no, &oqsr->port_no);
4791     }
4792
4793     case OFP10_VERSION: {
4794         const struct ofp10_queue_stats_request *qsr10 = ofpmsg_body(request);
4795         oqsr->queue_id = ntohl(qsr10->queue_id);
4796         oqsr->port_no = ntohs(qsr10->port_no);
4797         /* OF 1.0 uses OFPP_ALL for OFPP_ANY */
4798         if (oqsr->port_no == OFPP_ALL) {
4799             oqsr->port_no = OFPP_ANY;
4800         }
4801         return 0;
4802     }
4803
4804     default:
4805         NOT_REACHED();
4806     }
4807 }
4808
4809 /* Encode a queue statsrequest for 'oqsr', the encoded message
4810  * will be fore Open Flow version 'ofp_version'. Returns message
4811  * as a struct ofpbuf. Returns encoded message on success, NULL on error */
4812 struct ofpbuf *
4813 ofputil_encode_queue_stats_request(enum ofp_version ofp_version,
4814                                    const struct ofputil_queue_stats_request *oqsr)
4815 {
4816     struct ofpbuf *request;
4817
4818     switch (ofp_version) {
4819     case OFP11_VERSION:
4820     case OFP12_VERSION:
4821     case OFP13_VERSION: {
4822         struct ofp11_queue_stats_request *req;
4823         request = ofpraw_alloc(OFPRAW_OFPST11_QUEUE_REQUEST, ofp_version, 0);
4824         req = ofpbuf_put_zeros(request, sizeof *req);
4825         req->port_no = ofputil_port_to_ofp11(oqsr->port_no);
4826         req->queue_id = htonl(oqsr->queue_id);
4827         break;
4828     }
4829     case OFP10_VERSION: {
4830         struct ofp10_queue_stats_request *req;
4831         request = ofpraw_alloc(OFPRAW_OFPST10_QUEUE_REQUEST, ofp_version, 0);
4832         req = ofpbuf_put_zeros(request, sizeof *req);
4833         /* OpenFlow 1.0 needs OFPP_ALL instead of OFPP_ANY */
4834         req->port_no = htons(oqsr->port_no == OFPP_ANY
4835                              ? OFPP_ALL : oqsr->port_no);
4836         req->queue_id = htonl(oqsr->queue_id);
4837         break;
4838     }
4839     default:
4840         NOT_REACHED();
4841     }
4842
4843     return request;
4844 }
4845
4846 /* Returns the number of queue stats elements in OFPTYPE_QUEUE_STATS_REPLY
4847  * message 'oh'. */
4848 size_t
4849 ofputil_count_queue_stats(const struct ofp_header *oh)
4850 {
4851     struct ofpbuf b;
4852
4853     ofpbuf_use_const(&b, oh, ntohs(oh->length));
4854     ofpraw_pull_assert(&b);
4855
4856     BUILD_ASSERT(sizeof(struct ofp10_queue_stats) ==
4857                  sizeof(struct ofp11_queue_stats));
4858     return b.size / sizeof(struct ofp10_queue_stats);
4859 }
4860
4861 static enum ofperr
4862 ofputil_queue_stats_from_ofp10(struct ofputil_queue_stats *oqs,
4863                                const struct ofp10_queue_stats *qs10)
4864 {
4865     oqs->port_no = ntohs(qs10->port_no);
4866     oqs->queue_id = ntohl(qs10->queue_id);
4867     oqs->stats.tx_bytes = ntohll(get_32aligned_be64(&qs10->tx_bytes));
4868     oqs->stats.tx_packets = ntohll(get_32aligned_be64(&qs10->tx_packets));
4869     oqs->stats.tx_errors = ntohll(get_32aligned_be64(&qs10->tx_errors));
4870
4871     return 0;
4872 }
4873
4874 static enum ofperr
4875 ofputil_queue_stats_from_ofp11(struct ofputil_queue_stats *oqs,
4876                                const struct ofp11_queue_stats *qs11)
4877 {
4878     enum ofperr error;
4879
4880     error = ofputil_port_from_ofp11(qs11->port_no, &oqs->port_no);
4881     if (error) {
4882         return error;
4883     }
4884
4885     oqs->queue_id = ntohl(qs11->queue_id);
4886     oqs->stats.tx_bytes = ntohll(qs11->tx_bytes);
4887     oqs->stats.tx_packets = ntohll(qs11->tx_packets);
4888     oqs->stats.tx_errors = ntohll(qs11->tx_errors);
4889
4890     return 0;
4891 }
4892
4893 static enum ofperr
4894 ofputil_queue_stats_from_ofp13(struct ofputil_queue_stats *oqs,
4895                                const struct ofp13_queue_stats *qs13)
4896 {
4897     enum ofperr error
4898         = ofputil_queue_stats_from_ofp11(oqs, &qs13->qs);
4899     if (!error) {
4900         /* FIXME: Get qs13->duration_sec and qs13->duration_nsec,
4901          * Add to netdev_queue_stats? */
4902     }
4903
4904     return error;
4905 }
4906
4907 /* Converts an OFPST_QUEUE_STATS reply in 'msg' into an abstract
4908  * ofputil_queue_stats in 'qs'.
4909  *
4910  * Multiple OFPST_QUEUE_STATS replies can be packed into a single OpenFlow
4911  * message.  Calling this function multiple times for a single 'msg' iterates
4912  * through the replies.  The caller must initially leave 'msg''s layer pointers
4913  * null and not modify them between calls.
4914  *
4915  * Returns 0 if successful, EOF if no replies were left in this 'msg',
4916  * otherwise a positive errno value. */
4917 int
4918 ofputil_decode_queue_stats(struct ofputil_queue_stats *qs, struct ofpbuf *msg)
4919 {
4920     enum ofperr error;
4921     enum ofpraw raw;
4922
4923     error = (msg->l2
4924              ? ofpraw_decode(&raw, msg->l2)
4925              : ofpraw_pull(&raw, msg));
4926     if (error) {
4927         return error;
4928     }
4929
4930     if (!msg->size) {
4931         return EOF;
4932     } else if (raw == OFPRAW_OFPST13_QUEUE_REPLY) {
4933         const struct ofp13_queue_stats *qs13;
4934
4935         qs13 = ofpbuf_try_pull(msg, sizeof *qs13);
4936         if (!qs13) {
4937             goto bad_len;
4938         }
4939         return ofputil_queue_stats_from_ofp13(qs, qs13);
4940     } else if (raw == OFPRAW_OFPST11_QUEUE_REPLY) {
4941         const struct ofp11_queue_stats *qs11;
4942
4943         qs11 = ofpbuf_try_pull(msg, sizeof *qs11);
4944         if (!qs11) {
4945             goto bad_len;
4946         }
4947         return ofputil_queue_stats_from_ofp11(qs, qs11);
4948     } else if (raw == OFPRAW_OFPST10_QUEUE_REPLY) {
4949         const struct ofp10_queue_stats *qs10;
4950
4951         qs10 = ofpbuf_try_pull(msg, sizeof *qs10);
4952         if (!qs10) {
4953             goto bad_len;
4954         }
4955         return ofputil_queue_stats_from_ofp10(qs, qs10);
4956     } else {
4957         NOT_REACHED();
4958     }
4959
4960  bad_len:
4961     VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_QUEUE reply has %zu leftover "
4962                  "bytes at end", msg->size);
4963     return OFPERR_OFPBRC_BAD_LEN;
4964 }
4965
4966 static void
4967 ofputil_queue_stats_to_ofp10(const struct ofputil_queue_stats *oqs,
4968                              struct ofp10_queue_stats *qs10)
4969 {
4970     qs10->port_no = htons(oqs->port_no);
4971     memset(qs10->pad, 0, sizeof qs10->pad);
4972     qs10->queue_id = htonl(oqs->queue_id);
4973     put_32aligned_be64(&qs10->tx_bytes, htonll(oqs->stats.tx_bytes));
4974     put_32aligned_be64(&qs10->tx_packets, htonll(oqs->stats.tx_packets));
4975     put_32aligned_be64(&qs10->tx_errors, htonll(oqs->stats.tx_errors));
4976 }
4977
4978 static void
4979 ofputil_queue_stats_to_ofp11(const struct ofputil_queue_stats *oqs,
4980                              struct ofp11_queue_stats *qs11)
4981 {
4982     qs11->port_no = ofputil_port_to_ofp11(oqs->port_no);
4983     qs11->queue_id = htonl(oqs->queue_id);
4984     qs11->tx_bytes = htonll(oqs->stats.tx_bytes);
4985     qs11->tx_packets = htonll(oqs->stats.tx_packets);
4986     qs11->tx_errors = htonll(oqs->stats.tx_errors);
4987 }
4988
4989 static void
4990 ofputil_queue_stats_to_ofp13(const struct ofputil_queue_stats *oqs,
4991                              struct ofp13_queue_stats *qs13)
4992 {
4993     ofputil_queue_stats_to_ofp11(oqs, &qs13->qs);
4994     /* OF 1.3 adds duration fields */
4995     /* FIXME: Need to implement queue alive duration (sec + nsec) */
4996     qs13->duration_sec = htonl(~0);
4997     qs13->duration_nsec = htonl(~0);
4998 }
4999
5000 /* Encode a queue stat for 'oqs' and append it to 'replies'. */
5001 void
5002 ofputil_append_queue_stat(struct list *replies,
5003                           const struct ofputil_queue_stats *oqs)
5004 {
5005     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
5006     struct ofp_header *oh = msg->data;
5007
5008     switch ((enum ofp_version)oh->version) {
5009     case OFP13_VERSION: {
5010         struct ofp13_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
5011         ofputil_queue_stats_to_ofp13(oqs, reply);
5012         break;
5013     }
5014
5015     case OFP12_VERSION:
5016     case OFP11_VERSION: {
5017         struct ofp11_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
5018         ofputil_queue_stats_to_ofp11(oqs, reply);
5019         break;
5020     }
5021
5022     case OFP10_VERSION: {
5023         struct ofp10_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
5024         ofputil_queue_stats_to_ofp10(oqs, reply);
5025         break;
5026     }
5027
5028     default:
5029         NOT_REACHED();
5030     }
5031 }