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