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