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