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