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