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