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