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