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