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