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