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