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