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