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