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