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