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