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