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