ofproto: Break apart into generic and hardware-specific parts.
[sliver-openvswitch.git] / lib / ofp-util.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011 Nicira Networks.
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 <stdlib.h>
22 #include "autopath.h"
23 #include "byte-order.h"
24 #include "classifier.h"
25 #include "dynamic-string.h"
26 #include "multipath.h"
27 #include "nx-match.h"
28 #include "ofp-errors.h"
29 #include "ofp-util.h"
30 #include "ofpbuf.h"
31 #include "packets.h"
32 #include "random.h"
33 #include "unaligned.h"
34 #include "type-props.h"
35 #include "vlog.h"
36
37 VLOG_DEFINE_THIS_MODULE(ofp_util);
38
39 /* Rate limit for OpenFlow message parse errors.  These always indicate a bug
40  * in the peer and so there's not much point in showing a lot of them. */
41 static struct vlog_rate_limit bad_ofmsg_rl = VLOG_RATE_LIMIT_INIT(1, 5);
42
43 /* Given the wildcard bit count in the least-significant 6 of 'wcbits', returns
44  * an IP netmask with a 1 in each bit that must match and a 0 in each bit that
45  * is wildcarded.
46  *
47  * The bits in 'wcbits' are in the format used in enum ofp_flow_wildcards: 0
48  * is exact match, 1 ignores the LSB, 2 ignores the 2 least-significant bits,
49  * ..., 32 and higher wildcard the entire field.  This is the *opposite* of the
50  * usual convention where e.g. /24 indicates that 8 bits (not 24 bits) are
51  * wildcarded. */
52 ovs_be32
53 ofputil_wcbits_to_netmask(int wcbits)
54 {
55     wcbits &= 0x3f;
56     return wcbits < 32 ? htonl(~((1u << wcbits) - 1)) : 0;
57 }
58
59 /* Given the IP netmask 'netmask', returns the number of bits of the IP address
60  * that it wildcards.  'netmask' must be a CIDR netmask (see ip_is_cidr()). */
61 int
62 ofputil_netmask_to_wcbits(ovs_be32 netmask)
63 {
64     assert(ip_is_cidr(netmask));
65 #if __GNUC__ >= 4
66     return netmask == htonl(0) ? 32 : __builtin_ctz(ntohl(netmask));
67 #else
68     int wcbits;
69
70     for (wcbits = 32; netmask; wcbits--) {
71         netmask &= netmask - 1;
72     }
73
74     return wcbits;
75 #endif
76 }
77
78 /* A list of the FWW_* and OFPFW_ bits that have the same value, meaning, and
79  * name. */
80 #define WC_INVARIANT_LIST \
81     WC_INVARIANT_BIT(IN_PORT) \
82     WC_INVARIANT_BIT(DL_SRC) \
83     WC_INVARIANT_BIT(DL_DST) \
84     WC_INVARIANT_BIT(DL_TYPE) \
85     WC_INVARIANT_BIT(NW_PROTO) \
86     WC_INVARIANT_BIT(TP_SRC) \
87     WC_INVARIANT_BIT(TP_DST)
88
89 /* Verify that all of the invariant bits (as defined on WC_INVARIANT_LIST)
90  * actually have the same names and values. */
91 #define WC_INVARIANT_BIT(NAME) BUILD_ASSERT_DECL(FWW_##NAME == OFPFW_##NAME);
92     WC_INVARIANT_LIST
93 #undef WC_INVARIANT_BIT
94
95 /* WC_INVARIANTS is the invariant bits (as defined on WC_INVARIANT_LIST) all
96  * OR'd together. */
97 enum {
98     WC_INVARIANTS = 0
99 #define WC_INVARIANT_BIT(NAME) | FWW_##NAME
100     WC_INVARIANT_LIST
101 #undef WC_INVARIANT_BIT
102 };
103
104 /* Converts the ofp_match in 'match' into a cls_rule in 'rule', with the given
105  * 'priority'.
106  *
107  * 'flow_format' must either NXFF_OPENFLOW10 or NXFF_TUN_ID_FROM_COOKIE.  In
108  * the latter case only, 'flow''s tun_id field will be taken from the high bits
109  * of 'cookie', if 'match''s wildcards do not indicate that tun_id is
110  * wildcarded. */
111 void
112 ofputil_cls_rule_from_match(const struct ofp_match *match,
113                             unsigned int priority,
114                             enum nx_flow_format flow_format,
115                             ovs_be64 cookie, struct cls_rule *rule)
116 {
117     struct flow_wildcards *wc = &rule->wc;
118     unsigned int ofpfw;
119     ovs_be16 vid, pcp;
120
121     /* Initialize rule->priority. */
122     ofpfw = ntohl(match->wildcards);
123     ofpfw &= flow_format == NXFF_TUN_ID_FROM_COOKIE ? OVSFW_ALL : OFPFW_ALL;
124     rule->priority = !ofpfw ? UINT16_MAX : priority;
125
126     /* Initialize most of rule->wc. */
127     flow_wildcards_init_catchall(wc);
128     wc->wildcards = ofpfw & WC_INVARIANTS;
129
130     /* Wildcard fields that aren't defined by ofp_match or tun_id. */
131     wc->wildcards |= (FWW_ARP_SHA | FWW_ARP_THA | FWW_ND_TARGET);
132
133     if (ofpfw & OFPFW_NW_TOS) {
134         wc->wildcards |= FWW_NW_TOS;
135     }
136     wc->nw_src_mask = ofputil_wcbits_to_netmask(ofpfw >> OFPFW_NW_SRC_SHIFT);
137     wc->nw_dst_mask = ofputil_wcbits_to_netmask(ofpfw >> OFPFW_NW_DST_SHIFT);
138
139     if (flow_format == NXFF_TUN_ID_FROM_COOKIE && !(ofpfw & NXFW_TUN_ID)) {
140         cls_rule_set_tun_id(rule, htonll(ntohll(cookie) >> 32));
141     }
142
143     if (ofpfw & OFPFW_DL_DST) {
144         /* OpenFlow 1.0 OFPFW_DL_DST covers the whole Ethernet destination, but
145          * Open vSwitch breaks the Ethernet destination into bits as FWW_DL_DST
146          * and FWW_ETH_MCAST. */
147         wc->wildcards |= FWW_ETH_MCAST;
148     }
149
150     /* Initialize most of rule->flow. */
151     rule->flow.nw_src = match->nw_src;
152     rule->flow.nw_dst = match->nw_dst;
153     rule->flow.in_port = ntohs(match->in_port);
154     rule->flow.dl_type = ofputil_dl_type_from_openflow(match->dl_type);
155     rule->flow.tp_src = match->tp_src;
156     rule->flow.tp_dst = match->tp_dst;
157     memcpy(rule->flow.dl_src, match->dl_src, ETH_ADDR_LEN);
158     memcpy(rule->flow.dl_dst, match->dl_dst, ETH_ADDR_LEN);
159     rule->flow.nw_tos = match->nw_tos;
160     rule->flow.nw_proto = match->nw_proto;
161
162     /* Translate VLANs. */
163     vid = match->dl_vlan & htons(VLAN_VID_MASK);
164     pcp = htons((match->dl_vlan_pcp << VLAN_PCP_SHIFT) & VLAN_PCP_MASK);
165     switch (ofpfw & (OFPFW_DL_VLAN | OFPFW_DL_VLAN_PCP)) {
166     case OFPFW_DL_VLAN | OFPFW_DL_VLAN_PCP:
167         /* Wildcard everything. */
168         rule->flow.vlan_tci = htons(0);
169         rule->wc.vlan_tci_mask = htons(0);
170         break;
171
172     case OFPFW_DL_VLAN_PCP:
173         if (match->dl_vlan == htons(OFP_VLAN_NONE)) {
174             /* Match only packets without 802.1Q header. */
175             rule->flow.vlan_tci = htons(0);
176             rule->wc.vlan_tci_mask = htons(0xffff);
177         } else {
178             /* Wildcard PCP, specific VID. */
179             rule->flow.vlan_tci = vid | htons(VLAN_CFI);
180             rule->wc.vlan_tci_mask = htons(VLAN_VID_MASK | VLAN_CFI);
181         }
182         break;
183
184     case OFPFW_DL_VLAN:
185         /* Wildcard VID, specific PCP. */
186         rule->flow.vlan_tci = pcp | htons(VLAN_CFI);
187         rule->wc.vlan_tci_mask = htons(VLAN_PCP_MASK | VLAN_CFI);
188         break;
189
190     case 0:
191         if (match->dl_vlan == htons(OFP_VLAN_NONE)) {
192             /* This case is odd, since we can't have a specific PCP without an
193              * 802.1Q header.  However, older versions of OVS treated this as
194              * matching packets withut an 802.1Q header, so we do here too. */
195             rule->flow.vlan_tci = htons(0);
196             rule->wc.vlan_tci_mask = htons(0xffff);
197         } else {
198             /* Specific VID and PCP. */
199             rule->flow.vlan_tci = vid | pcp | htons(VLAN_CFI);
200             rule->wc.vlan_tci_mask = htons(0xffff);
201         }
202         break;
203     }
204
205     /* Clean up. */
206     cls_rule_zero_wildcarded_fields(rule);
207 }
208
209 /* Convert 'rule' into the OpenFlow match structure 'match'.  'flow_format'
210  * must either NXFF_OPENFLOW10 or NXFF_TUN_ID_FROM_COOKIE.
211  *
212  * The NXFF_TUN_ID_FROM_COOKIE flow format requires modifying the flow cookie.
213  * This function can help with that, if 'cookie_out' is nonnull.  For
214  * NXFF_OPENFLOW10, or if the tunnel ID is wildcarded, 'cookie_in' will be
215  * copied directly to '*cookie_out'.  For NXFF_TUN_ID_FROM_COOKIE when tunnel
216  * ID is matched, 'cookie_in' will be modified appropriately before setting
217  * '*cookie_out'.
218  */
219 void
220 ofputil_cls_rule_to_match(const struct cls_rule *rule,
221                           enum nx_flow_format flow_format,
222                           struct ofp_match *match,
223                           ovs_be64 cookie_in, ovs_be64 *cookie_out)
224 {
225     const struct flow_wildcards *wc = &rule->wc;
226     unsigned int ofpfw;
227
228     /* Figure out most OpenFlow wildcards. */
229     ofpfw = wc->wildcards & WC_INVARIANTS;
230     ofpfw |= ofputil_netmask_to_wcbits(wc->nw_src_mask) << OFPFW_NW_SRC_SHIFT;
231     ofpfw |= ofputil_netmask_to_wcbits(wc->nw_dst_mask) << OFPFW_NW_DST_SHIFT;
232     if (wc->wildcards & FWW_NW_TOS) {
233         ofpfw |= OFPFW_NW_TOS;
234     }
235
236     /* Tunnel ID. */
237     if (flow_format == NXFF_TUN_ID_FROM_COOKIE) {
238         if (wc->tun_id_mask == htonll(0)) {
239             ofpfw |= NXFW_TUN_ID;
240         } else {
241             uint32_t cookie_lo = ntohll(cookie_in);
242             uint32_t cookie_hi = ntohll(rule->flow.tun_id);
243             cookie_in = htonll(cookie_lo | ((uint64_t) cookie_hi << 32));
244         }
245     }
246     if (cookie_out) {
247         *cookie_out = cookie_in;
248     }
249
250     /* Translate VLANs. */
251     match->dl_vlan = htons(0);
252     match->dl_vlan_pcp = 0;
253     if (rule->wc.vlan_tci_mask == htons(0)) {
254         ofpfw |= OFPFW_DL_VLAN | OFPFW_DL_VLAN_PCP;
255     } else if (rule->wc.vlan_tci_mask & htons(VLAN_CFI)
256                && !(rule->flow.vlan_tci & htons(VLAN_CFI))) {
257         match->dl_vlan = htons(OFP_VLAN_NONE);
258     } else {
259         if (!(rule->wc.vlan_tci_mask & htons(VLAN_VID_MASK))) {
260             ofpfw |= OFPFW_DL_VLAN;
261         } else {
262             match->dl_vlan = htons(vlan_tci_to_vid(rule->flow.vlan_tci));
263         }
264
265         if (!(rule->wc.vlan_tci_mask & htons(VLAN_PCP_MASK))) {
266             ofpfw |= OFPFW_DL_VLAN_PCP;
267         } else {
268             match->dl_vlan_pcp = vlan_tci_to_pcp(rule->flow.vlan_tci);
269         }
270     }
271
272     /* Compose most of the match structure. */
273     match->wildcards = htonl(ofpfw);
274     match->in_port = htons(rule->flow.in_port);
275     memcpy(match->dl_src, rule->flow.dl_src, ETH_ADDR_LEN);
276     memcpy(match->dl_dst, rule->flow.dl_dst, ETH_ADDR_LEN);
277     match->dl_type = ofputil_dl_type_to_openflow(rule->flow.dl_type);
278     match->nw_src = rule->flow.nw_src;
279     match->nw_dst = rule->flow.nw_dst;
280     match->nw_tos = rule->flow.nw_tos;
281     match->nw_proto = rule->flow.nw_proto;
282     match->tp_src = rule->flow.tp_src;
283     match->tp_dst = rule->flow.tp_dst;
284     memset(match->pad1, '\0', sizeof match->pad1);
285     memset(match->pad2, '\0', sizeof match->pad2);
286 }
287
288 /* Given a 'dl_type' value in the format used in struct flow, returns the
289  * corresponding 'dl_type' value for use in an OpenFlow ofp_match structure. */
290 ovs_be16
291 ofputil_dl_type_to_openflow(ovs_be16 flow_dl_type)
292 {
293     return (flow_dl_type == htons(FLOW_DL_TYPE_NONE)
294             ? htons(OFP_DL_TYPE_NOT_ETH_TYPE)
295             : flow_dl_type);
296 }
297
298 /* Given a 'dl_type' value in the format used in an OpenFlow ofp_match
299  * structure, returns the corresponding 'dl_type' value for use in struct
300  * flow. */
301 ovs_be16
302 ofputil_dl_type_from_openflow(ovs_be16 ofp_dl_type)
303 {
304     return (ofp_dl_type == htons(OFP_DL_TYPE_NOT_ETH_TYPE)
305             ? htons(FLOW_DL_TYPE_NONE)
306             : ofp_dl_type);
307 }
308
309 /* Returns a transaction ID to use for an outgoing OpenFlow message. */
310 static ovs_be32
311 alloc_xid(void)
312 {
313     static uint32_t next_xid = 1;
314     return htonl(next_xid++);
315 }
316 \f
317 /* Basic parsing of OpenFlow messages. */
318
319 struct ofputil_msg_type {
320     enum ofputil_msg_code code; /* OFPUTIL_*. */
321     uint32_t value;             /* OFPT_*, OFPST_*, NXT_*, or NXST_*. */
322     const char *name;           /* e.g. "OFPT_FLOW_REMOVED". */
323     unsigned int min_size;      /* Minimum total message size in bytes. */
324     /* 0 if 'min_size' is the exact size that the message must be.  Otherwise,
325      * the message may exceed 'min_size' by an even multiple of this value. */
326     unsigned int extra_multiple;
327 };
328
329 struct ofputil_msg_category {
330     const char *name;           /* e.g. "OpenFlow message" */
331     const struct ofputil_msg_type *types;
332     size_t n_types;
333     int missing_error;          /* ofp_mkerr() value for missing type. */
334 };
335
336 static bool
337 ofputil_length_ok(const struct ofputil_msg_category *cat,
338                   const struct ofputil_msg_type *type,
339                   unsigned int size)
340 {
341     switch (type->extra_multiple) {
342     case 0:
343         if (size != type->min_size) {
344             VLOG_WARN_RL(&bad_ofmsg_rl, "received %s %s with incorrect "
345                          "length %u (expected length %u)",
346                          cat->name, type->name, size, type->min_size);
347             return false;
348         }
349         return true;
350
351     case 1:
352         if (size < type->min_size) {
353             VLOG_WARN_RL(&bad_ofmsg_rl, "received %s %s with incorrect "
354                          "length %u (expected length at least %u bytes)",
355                          cat->name, type->name, size, type->min_size);
356             return false;
357         }
358         return true;
359
360     default:
361         if (size < type->min_size
362             || (size - type->min_size) % type->extra_multiple) {
363             VLOG_WARN_RL(&bad_ofmsg_rl, "received %s %s with incorrect "
364                          "length %u (must be exactly %u bytes or longer "
365                          "by an integer multiple of %u bytes)",
366                          cat->name, type->name, size,
367                          type->min_size, type->extra_multiple);
368             return false;
369         }
370         return true;
371     }
372 }
373
374 static int
375 ofputil_lookup_openflow_message(const struct ofputil_msg_category *cat,
376                                 uint32_t value, unsigned int size,
377                                 const struct ofputil_msg_type **typep)
378 {
379     const struct ofputil_msg_type *type;
380
381     for (type = cat->types; type < &cat->types[cat->n_types]; type++) {
382         if (type->value == value) {
383             if (!ofputil_length_ok(cat, type, size)) {
384                 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
385             }
386             *typep = type;
387             return 0;
388         }
389     }
390
391     VLOG_WARN_RL(&bad_ofmsg_rl, "received %s of unknown type %"PRIu32,
392                  cat->name, value);
393     return cat->missing_error;
394 }
395
396 static int
397 ofputil_decode_vendor(const struct ofp_header *oh,
398                       const struct ofputil_msg_type **typep)
399 {
400     static const struct ofputil_msg_type nxt_messages[] = {
401         { OFPUTIL_NXT_TUN_ID_FROM_COOKIE,
402           NXT_TUN_ID_FROM_COOKIE, "NXT_TUN_ID_FROM_COOKIE",
403           sizeof(struct nxt_tun_id_cookie), 0 },
404
405         { OFPUTIL_NXT_ROLE_REQUEST,
406           NXT_ROLE_REQUEST, "NXT_ROLE_REQUEST",
407           sizeof(struct nx_role_request), 0 },
408
409         { OFPUTIL_NXT_ROLE_REPLY,
410           NXT_ROLE_REPLY, "NXT_ROLE_REPLY",
411           sizeof(struct nx_role_request), 0 },
412
413         { OFPUTIL_NXT_SET_FLOW_FORMAT,
414           NXT_SET_FLOW_FORMAT, "NXT_SET_FLOW_FORMAT",
415           sizeof(struct nxt_set_flow_format), 0 },
416
417         { OFPUTIL_NXT_FLOW_MOD,
418           NXT_FLOW_MOD, "NXT_FLOW_MOD",
419           sizeof(struct nx_flow_mod), 8 },
420
421         { OFPUTIL_NXT_FLOW_REMOVED,
422           NXT_FLOW_REMOVED, "NXT_FLOW_REMOVED",
423           sizeof(struct nx_flow_removed), 8 },
424     };
425
426     static const struct ofputil_msg_category nxt_category = {
427         "Nicira extension message",
428         nxt_messages, ARRAY_SIZE(nxt_messages),
429         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE)
430     };
431
432     const struct ofp_vendor_header *ovh;
433     const struct nicira_header *nh;
434
435     ovh = (const struct ofp_vendor_header *) oh;
436     if (ovh->vendor != htonl(NX_VENDOR_ID)) {
437         VLOG_WARN_RL(&bad_ofmsg_rl, "received vendor message for unknown "
438                      "vendor %"PRIx32, ntohl(ovh->vendor));
439         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_VENDOR);
440     }
441
442     if (ntohs(ovh->header.length) < sizeof(struct nicira_header)) {
443         VLOG_WARN_RL(&bad_ofmsg_rl, "received Nicira vendor message of "
444                      "length %u (expected at least %zu)",
445                      ntohs(ovh->header.length), sizeof(struct nicira_header));
446         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
447     }
448
449     nh = (const struct nicira_header *) oh;
450     return ofputil_lookup_openflow_message(&nxt_category, ntohl(nh->subtype),
451                                            ntohs(oh->length), typep);
452 }
453
454 static int
455 check_nxstats_msg(const struct ofp_header *oh)
456 {
457     const struct ofp_stats_request *osr;
458     ovs_be32 vendor;
459
460     osr = (const struct ofp_stats_request *) oh;
461
462     memcpy(&vendor, osr->body, sizeof vendor);
463     if (vendor != htonl(NX_VENDOR_ID)) {
464         VLOG_WARN_RL(&bad_ofmsg_rl, "received vendor stats message for "
465                      "unknown vendor %"PRIx32, ntohl(vendor));
466         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_VENDOR);
467     }
468
469     if (ntohs(osr->header.length) < sizeof(struct nicira_stats_msg)) {
470         VLOG_WARN_RL(&bad_ofmsg_rl, "truncated Nicira stats message");
471         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
472     }
473
474     return 0;
475 }
476
477 static int
478 ofputil_decode_nxst_request(const struct ofp_header *oh,
479                             const struct ofputil_msg_type **typep)
480 {
481     static const struct ofputil_msg_type nxst_requests[] = {
482         { OFPUTIL_NXST_FLOW_REQUEST,
483           NXST_FLOW, "NXST_FLOW request",
484           sizeof(struct nx_flow_stats_request), 8 },
485
486         { OFPUTIL_NXST_AGGREGATE_REQUEST,
487           NXST_AGGREGATE, "NXST_AGGREGATE request",
488           sizeof(struct nx_aggregate_stats_request), 8 },
489     };
490
491     static const struct ofputil_msg_category nxst_request_category = {
492         "Nicira extension statistics request",
493         nxst_requests, ARRAY_SIZE(nxst_requests),
494         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE)
495     };
496
497     const struct nicira_stats_msg *nsm;
498     int error;
499
500     error = check_nxstats_msg(oh);
501     if (error) {
502         return error;
503     }
504
505     nsm = (struct nicira_stats_msg *) oh;
506     return ofputil_lookup_openflow_message(&nxst_request_category,
507                                            ntohl(nsm->subtype),
508                                            ntohs(oh->length), typep);
509 }
510
511 static int
512 ofputil_decode_nxst_reply(const struct ofp_header *oh,
513                           const struct ofputil_msg_type **typep)
514 {
515     static const struct ofputil_msg_type nxst_replies[] = {
516         { OFPUTIL_NXST_FLOW_REPLY,
517           NXST_FLOW, "NXST_FLOW reply",
518           sizeof(struct nicira_stats_msg), 8 },
519
520         { OFPUTIL_NXST_AGGREGATE_REPLY,
521           NXST_AGGREGATE, "NXST_AGGREGATE reply",
522           sizeof(struct nx_aggregate_stats_reply), 0 },
523     };
524
525     static const struct ofputil_msg_category nxst_reply_category = {
526         "Nicira extension statistics reply",
527         nxst_replies, ARRAY_SIZE(nxst_replies),
528         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_SUBTYPE)
529     };
530
531     const struct nicira_stats_msg *nsm;
532     int error;
533
534     error = check_nxstats_msg(oh);
535     if (error) {
536         return error;
537     }
538
539     nsm = (struct nicira_stats_msg *) oh;
540     return ofputil_lookup_openflow_message(&nxst_reply_category,
541                                            ntohl(nsm->subtype),
542                                            ntohs(oh->length), typep);
543 }
544
545 static int
546 ofputil_decode_ofpst_request(const struct ofp_header *oh,
547                              const struct ofputil_msg_type **typep)
548 {
549     enum { OSR_SIZE = sizeof(struct ofp_stats_request) };
550     static const struct ofputil_msg_type ofpst_requests[] = {
551         { OFPUTIL_OFPST_DESC_REQUEST,
552           OFPST_DESC, "OFPST_DESC request",
553           OSR_SIZE, 0 },
554
555         { OFPUTIL_OFPST_FLOW_REQUEST,
556           OFPST_FLOW, "OFPST_FLOW request",
557           OSR_SIZE + sizeof(struct ofp_flow_stats_request), 0 },
558
559         { OFPUTIL_OFPST_AGGREGATE_REQUEST,
560           OFPST_AGGREGATE, "OFPST_AGGREGATE request",
561           OSR_SIZE + sizeof(struct ofp_aggregate_stats_request), 0 },
562
563         { OFPUTIL_OFPST_TABLE_REQUEST,
564           OFPST_TABLE, "OFPST_TABLE request",
565           OSR_SIZE, 0 },
566
567         { OFPUTIL_OFPST_PORT_REQUEST,
568           OFPST_PORT, "OFPST_PORT request",
569           OSR_SIZE + sizeof(struct ofp_port_stats_request), 0 },
570
571         { OFPUTIL_OFPST_QUEUE_REQUEST,
572           OFPST_QUEUE, "OFPST_QUEUE request",
573           OSR_SIZE + sizeof(struct ofp_queue_stats_request), 0 },
574
575         { 0,
576           OFPST_VENDOR, "OFPST_VENDOR request",
577           OSR_SIZE + sizeof(uint32_t), 1 },
578     };
579
580     static const struct ofputil_msg_category ofpst_request_category = {
581         "OpenFlow statistics",
582         ofpst_requests, ARRAY_SIZE(ofpst_requests),
583         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT)
584     };
585
586     const struct ofp_stats_request *osr;
587     int error;
588
589     osr = (const struct ofp_stats_request *) oh;
590     error = ofputil_lookup_openflow_message(&ofpst_request_category,
591                                             ntohs(osr->type),
592                                             ntohs(oh->length), typep);
593     if (!error && osr->type == htons(OFPST_VENDOR)) {
594         error = ofputil_decode_nxst_request(oh, typep);
595     }
596     return error;
597 }
598
599 static int
600 ofputil_decode_ofpst_reply(const struct ofp_header *oh,
601                            const struct ofputil_msg_type **typep)
602 {
603     enum { OSR_SIZE = sizeof(struct ofp_stats_reply) };
604     static const struct ofputil_msg_type ofpst_replies[] = {
605         { OFPUTIL_OFPST_DESC_REPLY,
606           OFPST_DESC, "OFPST_DESC reply",
607           OSR_SIZE + sizeof(struct ofp_desc_stats), 0 },
608
609         { OFPUTIL_OFPST_FLOW_REPLY,
610           OFPST_FLOW, "OFPST_FLOW reply",
611           OSR_SIZE, 1 },
612
613         { OFPUTIL_OFPST_AGGREGATE_REPLY,
614           OFPST_AGGREGATE, "OFPST_AGGREGATE reply",
615           OSR_SIZE + sizeof(struct ofp_aggregate_stats_reply), 0 },
616
617         { OFPUTIL_OFPST_TABLE_REPLY,
618           OFPST_TABLE, "OFPST_TABLE reply",
619           OSR_SIZE, sizeof(struct ofp_table_stats) },
620
621         { OFPUTIL_OFPST_PORT_REPLY,
622           OFPST_PORT, "OFPST_PORT reply",
623           OSR_SIZE, sizeof(struct ofp_port_stats) },
624
625         { OFPUTIL_OFPST_QUEUE_REPLY,
626           OFPST_QUEUE, "OFPST_QUEUE reply",
627           OSR_SIZE, sizeof(struct ofp_queue_stats) },
628
629         { 0,
630           OFPST_VENDOR, "OFPST_VENDOR reply",
631           OSR_SIZE + sizeof(uint32_t), 1 },
632     };
633
634     static const struct ofputil_msg_category ofpst_reply_category = {
635         "OpenFlow statistics",
636         ofpst_replies, ARRAY_SIZE(ofpst_replies),
637         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT)
638     };
639
640     const struct ofp_stats_reply *osr = (const struct ofp_stats_reply *) oh;
641     int error;
642
643     error = ofputil_lookup_openflow_message(&ofpst_reply_category,
644                                            ntohs(osr->type),
645                                            ntohs(oh->length), typep);
646     if (!error && osr->type == htons(OFPST_VENDOR)) {
647         error = ofputil_decode_nxst_reply(oh, typep);
648     }
649     return error;
650 }
651
652 /* Decodes the message type represented by 'oh'.  Returns 0 if successful or
653  * an OpenFlow error code constructed with ofp_mkerr() on failure.  Either
654  * way, stores in '*typep' a type structure that can be inspected with the
655  * ofputil_msg_type_*() functions.
656  *
657  * oh->length must indicate the correct length of the message (and must be at
658  * least sizeof(struct ofp_header)).
659  *
660  * Success indicates that 'oh' is at least as long as the minimum-length
661  * message of its type. */
662 int
663 ofputil_decode_msg_type(const struct ofp_header *oh,
664                         const struct ofputil_msg_type **typep)
665 {
666     static const struct ofputil_msg_type ofpt_messages[] = {
667         { OFPUTIL_OFPT_HELLO,
668           OFPT_HELLO, "OFPT_HELLO",
669           sizeof(struct ofp_hello), 1 },
670
671         { OFPUTIL_OFPT_ERROR,
672           OFPT_ERROR, "OFPT_ERROR",
673           sizeof(struct ofp_error_msg), 1 },
674
675         { OFPUTIL_OFPT_ECHO_REQUEST,
676           OFPT_ECHO_REQUEST, "OFPT_ECHO_REQUEST",
677           sizeof(struct ofp_header), 1 },
678
679         { OFPUTIL_OFPT_ECHO_REPLY,
680           OFPT_ECHO_REPLY, "OFPT_ECHO_REPLY",
681           sizeof(struct ofp_header), 1 },
682
683         { OFPUTIL_OFPT_FEATURES_REQUEST,
684           OFPT_FEATURES_REQUEST, "OFPT_FEATURES_REQUEST",
685           sizeof(struct ofp_header), 0 },
686
687         { OFPUTIL_OFPT_FEATURES_REPLY,
688           OFPT_FEATURES_REPLY, "OFPT_FEATURES_REPLY",
689           sizeof(struct ofp_switch_features), sizeof(struct ofp_phy_port) },
690
691         { OFPUTIL_OFPT_GET_CONFIG_REQUEST,
692           OFPT_GET_CONFIG_REQUEST, "OFPT_GET_CONFIG_REQUEST",
693           sizeof(struct ofp_header), 0 },
694
695         { OFPUTIL_OFPT_GET_CONFIG_REPLY,
696           OFPT_GET_CONFIG_REPLY, "OFPT_GET_CONFIG_REPLY",
697           sizeof(struct ofp_switch_config), 0 },
698
699         { OFPUTIL_OFPT_SET_CONFIG,
700           OFPT_SET_CONFIG, "OFPT_SET_CONFIG",
701           sizeof(struct ofp_switch_config), 0 },
702
703         { OFPUTIL_OFPT_PACKET_IN,
704           OFPT_PACKET_IN, "OFPT_PACKET_IN",
705           offsetof(struct ofp_packet_in, data), 1 },
706
707         { OFPUTIL_OFPT_FLOW_REMOVED,
708           OFPT_FLOW_REMOVED, "OFPT_FLOW_REMOVED",
709           sizeof(struct ofp_flow_removed), 0 },
710
711         { OFPUTIL_OFPT_PORT_STATUS,
712           OFPT_PORT_STATUS, "OFPT_PORT_STATUS",
713           sizeof(struct ofp_port_status), 0 },
714
715         { OFPUTIL_OFPT_PACKET_OUT,
716           OFPT_PACKET_OUT, "OFPT_PACKET_OUT",
717           sizeof(struct ofp_packet_out), 1 },
718
719         { OFPUTIL_OFPT_FLOW_MOD,
720           OFPT_FLOW_MOD, "OFPT_FLOW_MOD",
721           sizeof(struct ofp_flow_mod), 1 },
722
723         { OFPUTIL_OFPT_PORT_MOD,
724           OFPT_PORT_MOD, "OFPT_PORT_MOD",
725           sizeof(struct ofp_port_mod), 0 },
726
727         { 0,
728           OFPT_STATS_REQUEST, "OFPT_STATS_REQUEST",
729           sizeof(struct ofp_stats_request), 1 },
730
731         { 0,
732           OFPT_STATS_REPLY, "OFPT_STATS_REPLY",
733           sizeof(struct ofp_stats_reply), 1 },
734
735         { OFPUTIL_OFPT_BARRIER_REQUEST,
736           OFPT_BARRIER_REQUEST, "OFPT_BARRIER_REQUEST",
737           sizeof(struct ofp_header), 0 },
738
739         { OFPUTIL_OFPT_BARRIER_REPLY,
740           OFPT_BARRIER_REPLY, "OFPT_BARRIER_REPLY",
741           sizeof(struct ofp_header), 0 },
742
743         { 0,
744           OFPT_VENDOR, "OFPT_VENDOR",
745           sizeof(struct ofp_vendor_header), 1 },
746     };
747
748     static const struct ofputil_msg_category ofpt_category = {
749         "OpenFlow message",
750         ofpt_messages, ARRAY_SIZE(ofpt_messages),
751         OFP_MKERR(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE)
752     };
753
754     int error;
755
756     error = ofputil_lookup_openflow_message(&ofpt_category, oh->type,
757                                             ntohs(oh->length), typep);
758     if (!error) {
759         switch (oh->type) {
760         case OFPT_VENDOR:
761             error = ofputil_decode_vendor(oh, typep);
762             break;
763
764         case OFPT_STATS_REQUEST:
765             error = ofputil_decode_ofpst_request(oh, typep);
766             break;
767
768         case OFPT_STATS_REPLY:
769             error = ofputil_decode_ofpst_reply(oh, typep);
770
771         default:
772             break;
773         }
774     }
775     if (error) {
776         static const struct ofputil_msg_type ofputil_invalid_type = {
777             OFPUTIL_INVALID,
778             0, "OFPUTIL_INVALID",
779             0, 0
780         };
781
782         *typep = &ofputil_invalid_type;
783     }
784     return error;
785 }
786
787 /* Returns an OFPUTIL_* message type code for 'type'. */
788 enum ofputil_msg_code
789 ofputil_msg_type_code(const struct ofputil_msg_type *type)
790 {
791     return type->code;
792 }
793 \f
794 /* Flow formats. */
795
796 bool
797 ofputil_flow_format_is_valid(enum nx_flow_format flow_format)
798 {
799     switch (flow_format) {
800     case NXFF_OPENFLOW10:
801     case NXFF_TUN_ID_FROM_COOKIE:
802     case NXFF_NXM:
803         return true;
804     }
805
806     return false;
807 }
808
809 const char *
810 ofputil_flow_format_to_string(enum nx_flow_format flow_format)
811 {
812     switch (flow_format) {
813     case NXFF_OPENFLOW10:
814         return "openflow10";
815     case NXFF_TUN_ID_FROM_COOKIE:
816         return "tun_id_from_cookie";
817     case NXFF_NXM:
818         return "nxm";
819     default:
820         NOT_REACHED();
821     }
822 }
823
824 int
825 ofputil_flow_format_from_string(const char *s)
826 {
827     return (!strcmp(s, "openflow10") ? NXFF_OPENFLOW10
828             : !strcmp(s, "tun_id_from_cookie") ? NXFF_TUN_ID_FROM_COOKIE
829             : !strcmp(s, "nxm") ? NXFF_NXM
830             : -1);
831 }
832
833 static bool
834 regs_fully_wildcarded(const struct flow_wildcards *wc)
835 {
836     int i;
837
838     for (i = 0; i < FLOW_N_REGS; i++) {
839         if (wc->reg_masks[i] != 0) {
840             return false;
841         }
842     }
843     return true;
844 }
845
846 static inline bool
847 is_nxm_required(const struct cls_rule *rule, bool cookie_support,
848                 ovs_be64 cookie)
849 {
850     const struct flow_wildcards *wc = &rule->wc;
851     uint32_t cookie_hi;
852     uint64_t tun_id;
853
854     /* Only NXM supports separately wildcards the Ethernet multicast bit. */
855     if (!(wc->wildcards & FWW_DL_DST) != !(wc->wildcards & FWW_ETH_MCAST)) {
856         return true;
857     }
858
859     /* Only NXM supports matching ARP hardware addresses. */
860     if (!(wc->wildcards & FWW_ARP_SHA) || !(wc->wildcards & FWW_ARP_THA)) {
861         return true;
862     }
863
864     /* Only NXM supports matching IPv6 traffic. */
865     if (!(wc->wildcards & FWW_DL_TYPE)
866             && (rule->flow.dl_type == htons(ETH_TYPE_IPV6))) {
867         return true;
868     }
869
870     /* Only NXM supports matching registers. */
871     if (!regs_fully_wildcarded(wc)) {
872         return true;
873     }
874
875     switch (wc->tun_id_mask) {
876     case CONSTANT_HTONLL(0):
877         /* Other formats can fully wildcard tun_id. */
878         break;
879
880     case CONSTANT_HTONLL(UINT64_MAX):
881         /* Only NXM supports tunnel ID matching without a cookie. */
882         if (!cookie_support) {
883             return true;
884         }
885
886         /* Only NXM supports 64-bit tunnel IDs. */
887         tun_id = ntohll(rule->flow.tun_id);
888         if (tun_id > UINT32_MAX) {
889             return true;
890         }
891
892         /* Only NXM supports a cookie whose top 32 bits conflict with the
893          * tunnel ID. */
894         cookie_hi = ntohll(cookie) >> 32;
895         if (cookie_hi && cookie_hi != tun_id) {
896             return true;
897         }
898         break;
899
900     default:
901         /* Only NXM supports partial matches on tunnel ID. */
902         return true;
903     }
904
905     /* Other formats can express this rule. */
906     return false;
907 }
908
909 /* Returns the minimum nx_flow_format to use for sending 'rule' to a switch
910  * (e.g. to add or remove a flow).  'cookie_support' should be true if the
911  * command to be sent includes a flow cookie (as OFPT_FLOW_MOD does, for
912  * example) or false if the command does not (OFPST_FLOW and OFPST_AGGREGATE do
913  * not, for example).  If 'cookie_support' is true, then 'cookie' should be the
914  * cookie to be sent; otherwise its value is ignored.
915  *
916  * The "best" flow format is chosen on this basis:
917  *
918  *   - It must be capable of expressing the rule.  NXFF_OPENFLOW10 flows can't
919  *     handle tunnel IDs.  NXFF_TUN_ID_FROM_COOKIE flows can't handle registers
920  *     or fixing the Ethernet multicast bit, and can't handle tunnel IDs that
921  *     conflict with the high 32 bits of the cookie or commands that don't
922  *     support cookies.
923  *
924  *   - Otherwise, the chosen format should be as backward compatible as
925  *     possible.  (NXFF_OPENFLOW10 is more backward compatible than
926  *     NXFF_TUN_ID_FROM_COOKIE, which is more backward compatible than
927  *     NXFF_NXM.)
928  */
929 enum nx_flow_format
930 ofputil_min_flow_format(const struct cls_rule *rule, bool cookie_support,
931                         ovs_be64 cookie)
932 {
933     if (is_nxm_required(rule, cookie_support, cookie)) {
934         return NXFF_NXM;
935     } else if (rule->wc.tun_id_mask != htonll(0)) {
936         return NXFF_TUN_ID_FROM_COOKIE;
937     } else {
938         return NXFF_OPENFLOW10;
939     }
940 }
941
942 /* Returns an OpenFlow message that can be used to set the flow format to
943  * 'flow_format'.  */
944 struct ofpbuf *
945 ofputil_make_set_flow_format(enum nx_flow_format flow_format)
946 {
947     struct ofpbuf *msg;
948
949     if (flow_format == NXFF_OPENFLOW10
950         || flow_format == NXFF_TUN_ID_FROM_COOKIE) {
951         struct nxt_tun_id_cookie *tic;
952
953         tic = make_nxmsg(sizeof *tic, NXT_TUN_ID_FROM_COOKIE, &msg);
954         tic->set = flow_format == NXFF_TUN_ID_FROM_COOKIE;
955     } else {
956         struct nxt_set_flow_format *sff;
957
958         sff = make_nxmsg(sizeof *sff, NXT_SET_FLOW_FORMAT, &msg);
959         sff->format = htonl(flow_format);
960     }
961
962     return msg;
963 }
964
965 /* Converts an OFPT_FLOW_MOD or NXT_FLOW_MOD message 'oh' into an abstract
966  * flow_mod in 'fm'.  Returns 0 if successful, otherwise an OpenFlow error
967  * code.
968  *
969  * For OFPT_FLOW_MOD messages, 'flow_format' should be the current flow format
970  * at the time when the message was received.  Otherwise 'flow_format' is
971  * ignored.
972  *
973  * Does not validate the flow_mod actions. */
974 int
975 ofputil_decode_flow_mod(struct flow_mod *fm, const struct ofp_header *oh,
976                         enum nx_flow_format flow_format)
977 {
978     const struct ofputil_msg_type *type;
979     struct ofpbuf b;
980
981     ofpbuf_use_const(&b, oh, ntohs(oh->length));
982
983     ofputil_decode_msg_type(oh, &type);
984     if (ofputil_msg_type_code(type) == OFPUTIL_OFPT_FLOW_MOD) {
985         /* Standard OpenFlow flow_mod. */
986         struct ofp_match match, orig_match;
987         const struct ofp_flow_mod *ofm;
988         int error;
989
990         /* Dissect the message. */
991         ofm = ofpbuf_pull(&b, sizeof *ofm);
992         error = ofputil_pull_actions(&b, b.size, &fm->actions, &fm->n_actions);
993         if (error) {
994             return error;
995         }
996
997         /* Normalize ofm->match.  If normalization actually changes anything,
998          * then log the differences. */
999         match = ofm->match;
1000         match.pad1[0] = match.pad2[0] = 0;
1001         orig_match = match;
1002         normalize_match(&match);
1003         if (memcmp(&match, &orig_match, sizeof orig_match)) {
1004             if (!VLOG_DROP_INFO(&bad_ofmsg_rl)) {
1005                 char *old = ofp_match_to_literal_string(&orig_match);
1006                 char *new = ofp_match_to_literal_string(&match);
1007                 VLOG_INFO("normalization changed ofp_match, details:");
1008                 VLOG_INFO(" pre: %s", old);
1009                 VLOG_INFO("post: %s", new);
1010                 free(old);
1011                 free(new);
1012             }
1013         }
1014
1015         /* Translate the message. */
1016         ofputil_cls_rule_from_match(&match, ntohs(ofm->priority), flow_format,
1017                                     ofm->cookie, &fm->cr);
1018         fm->cookie = ofm->cookie;
1019         fm->command = ntohs(ofm->command);
1020         fm->idle_timeout = ntohs(ofm->idle_timeout);
1021         fm->hard_timeout = ntohs(ofm->hard_timeout);
1022         fm->buffer_id = ntohl(ofm->buffer_id);
1023         fm->out_port = ntohs(ofm->out_port);
1024         fm->flags = ntohs(ofm->flags);
1025     } else if (ofputil_msg_type_code(type) == OFPUTIL_NXT_FLOW_MOD) {
1026         /* Nicira extended flow_mod. */
1027         const struct nx_flow_mod *nfm;
1028         int error;
1029
1030         /* Dissect the message. */
1031         nfm = ofpbuf_pull(&b, sizeof *nfm);
1032         error = nx_pull_match(&b, ntohs(nfm->match_len), ntohs(nfm->priority),
1033                               &fm->cr);
1034         if (error) {
1035             return error;
1036         }
1037         error = ofputil_pull_actions(&b, b.size, &fm->actions, &fm->n_actions);
1038         if (error) {
1039             return error;
1040         }
1041
1042         /* Translate the message. */
1043         fm->cookie = nfm->cookie;
1044         fm->command = ntohs(nfm->command);
1045         fm->idle_timeout = ntohs(nfm->idle_timeout);
1046         fm->hard_timeout = ntohs(nfm->hard_timeout);
1047         fm->buffer_id = ntohl(nfm->buffer_id);
1048         fm->out_port = ntohs(nfm->out_port);
1049         fm->flags = ntohs(nfm->flags);
1050     } else {
1051         NOT_REACHED();
1052     }
1053
1054     return 0;
1055 }
1056
1057 /* Converts 'fm' into an OFPT_FLOW_MOD or NXT_FLOW_MOD message according to
1058  * 'flow_format' and returns the message. */
1059 struct ofpbuf *
1060 ofputil_encode_flow_mod(const struct flow_mod *fm,
1061                         enum nx_flow_format flow_format)
1062 {
1063     size_t actions_len = fm->n_actions * sizeof *fm->actions;
1064     struct ofpbuf *msg;
1065
1066     if (flow_format == NXFF_OPENFLOW10
1067         || flow_format == NXFF_TUN_ID_FROM_COOKIE) {
1068         struct ofp_flow_mod *ofm;
1069
1070         msg = ofpbuf_new(sizeof *ofm + actions_len);
1071         ofm = put_openflow(sizeof *ofm, OFPT_FLOW_MOD, msg);
1072         ofputil_cls_rule_to_match(&fm->cr, flow_format, &ofm->match,
1073                                   fm->cookie, &ofm->cookie);
1074         ofm->command = htons(fm->command);
1075         ofm->idle_timeout = htons(fm->idle_timeout);
1076         ofm->hard_timeout = htons(fm->hard_timeout);
1077         ofm->priority = htons(fm->cr.priority);
1078         ofm->buffer_id = htonl(fm->buffer_id);
1079         ofm->out_port = htons(fm->out_port);
1080         ofm->flags = htons(fm->flags);
1081     } else if (flow_format == NXFF_NXM) {
1082         struct nx_flow_mod *nfm;
1083         int match_len;
1084
1085         msg = ofpbuf_new(sizeof *nfm + NXM_TYPICAL_LEN + actions_len);
1086         put_nxmsg(sizeof *nfm, NXT_FLOW_MOD, msg);
1087         match_len = nx_put_match(msg, &fm->cr);
1088
1089         nfm = msg->data;
1090         nfm->cookie = fm->cookie;
1091         nfm->command = htons(fm->command);
1092         nfm->idle_timeout = htons(fm->idle_timeout);
1093         nfm->hard_timeout = htons(fm->hard_timeout);
1094         nfm->priority = htons(fm->cr.priority);
1095         nfm->buffer_id = htonl(fm->buffer_id);
1096         nfm->out_port = htons(fm->out_port);
1097         nfm->flags = htons(fm->flags);
1098         nfm->match_len = htons(match_len);
1099     } else {
1100         NOT_REACHED();
1101     }
1102
1103     ofpbuf_put(msg, fm->actions, actions_len);
1104     update_openflow_length(msg);
1105     return msg;
1106 }
1107
1108 static int
1109 ofputil_decode_ofpst_flow_request(struct flow_stats_request *fsr,
1110                                   const struct ofp_header *oh,
1111                                   enum nx_flow_format flow_format,
1112                                   bool aggregate)
1113 {
1114     const struct ofp_flow_stats_request *ofsr = ofputil_stats_body(oh);
1115
1116     fsr->aggregate = aggregate;
1117     ofputil_cls_rule_from_match(&ofsr->match, 0, flow_format, 0, &fsr->match);
1118     fsr->out_port = ntohs(ofsr->out_port);
1119     fsr->table_id = ofsr->table_id;
1120
1121     return 0;
1122 }
1123
1124 static int
1125 ofputil_decode_nxst_flow_request(struct flow_stats_request *fsr,
1126                                  const struct ofp_header *oh,
1127                                  bool aggregate)
1128 {
1129     const struct nx_flow_stats_request *nfsr;
1130     struct ofpbuf b;
1131     int error;
1132
1133     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1134
1135     nfsr = ofpbuf_pull(&b, sizeof *nfsr);
1136     error = nx_pull_match(&b, ntohs(nfsr->match_len), 0, &fsr->match);
1137     if (error) {
1138         return error;
1139     }
1140     if (b.size) {
1141         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1142     }
1143
1144     fsr->aggregate = aggregate;
1145     fsr->out_port = ntohs(nfsr->out_port);
1146     fsr->table_id = nfsr->table_id;
1147
1148     return 0;
1149 }
1150
1151 /* Converts an OFPST_FLOW, OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE
1152  * request 'oh', received when the current flow format was 'flow_format', into
1153  * an abstract flow_stats_request in 'fsr'.  Returns 0 if successful, otherwise
1154  * an OpenFlow error code.
1155  *
1156  * For OFPST_FLOW and OFPST_AGGREGATE messages, 'flow_format' should be the
1157  * current flow format at the time when the message was received.  Otherwise
1158  * 'flow_format' is ignored. */
1159 int
1160 ofputil_decode_flow_stats_request(struct flow_stats_request *fsr,
1161                                   const struct ofp_header *oh,
1162                                   enum nx_flow_format flow_format)
1163 {
1164     const struct ofputil_msg_type *type;
1165     struct ofpbuf b;
1166     int code;
1167
1168     ofpbuf_use_const(&b, oh, ntohs(oh->length));
1169
1170     ofputil_decode_msg_type(oh, &type);
1171     code = ofputil_msg_type_code(type);
1172     switch (code) {
1173     case OFPUTIL_OFPST_FLOW_REQUEST:
1174         return ofputil_decode_ofpst_flow_request(fsr, oh, flow_format, false);
1175
1176     case OFPUTIL_OFPST_AGGREGATE_REQUEST:
1177         return ofputil_decode_ofpst_flow_request(fsr, oh, flow_format, true);
1178
1179     case OFPUTIL_NXST_FLOW_REQUEST:
1180         return ofputil_decode_nxst_flow_request(fsr, oh, false);
1181
1182     case OFPUTIL_NXST_AGGREGATE_REQUEST:
1183         return ofputil_decode_nxst_flow_request(fsr, oh, true);
1184
1185     default:
1186         /* Hey, the caller lied. */
1187         NOT_REACHED();
1188     }
1189 }
1190
1191 /* Converts abstract flow_stats_request 'fsr' into an OFPST_FLOW,
1192  * OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE request 'oh' according to
1193  * 'flow_format', and returns the message. */
1194 struct ofpbuf *
1195 ofputil_encode_flow_stats_request(const struct flow_stats_request *fsr,
1196                                   enum nx_flow_format flow_format)
1197 {
1198     struct ofpbuf *msg;
1199
1200     if (flow_format == NXFF_OPENFLOW10
1201         || flow_format == NXFF_TUN_ID_FROM_COOKIE) {
1202         struct ofp_flow_stats_request *ofsr;
1203         int type;
1204
1205         BUILD_ASSERT_DECL(sizeof(struct ofp_flow_stats_request)
1206                           == sizeof(struct ofp_aggregate_stats_request));
1207
1208         type = fsr->aggregate ? OFPST_AGGREGATE : OFPST_FLOW;
1209         ofsr = ofputil_make_stats_request(sizeof *ofsr, type, &msg);
1210         ofputil_cls_rule_to_match(&fsr->match, flow_format, &ofsr->match,
1211                                   0, NULL);
1212         ofsr->table_id = fsr->table_id;
1213         ofsr->out_port = htons(fsr->out_port);
1214     } else if (flow_format == NXFF_NXM) {
1215         struct nx_flow_stats_request *nfsr;
1216         int match_len;
1217         int subtype;
1218
1219         subtype = fsr->aggregate ? NXST_AGGREGATE : NXST_FLOW;
1220         ofputil_make_nxstats_request(sizeof *nfsr, subtype, &msg);
1221         match_len = nx_put_match(msg, &fsr->match);
1222
1223         nfsr = msg->data;
1224         nfsr->out_port = htons(fsr->out_port);
1225         nfsr->match_len = htons(match_len);
1226         nfsr->table_id = fsr->table_id;
1227     } else {
1228         NOT_REACHED();
1229     }
1230
1231     return msg;
1232 }
1233
1234 /* Converts an OFPST_FLOW or NXST_FLOW reply in 'msg' into an abstract
1235  * ofputil_flow_stats in 'fs'.  For OFPST_FLOW messages, 'flow_format' should
1236  * be the current flow format at the time when the request corresponding to the
1237  * reply in 'msg' was sent.  Otherwise 'flow_format' is ignored.
1238  *
1239  * Multiple OFPST_FLOW or NXST_FLOW replies can be packed into a single
1240  * OpenFlow message.  Calling this function multiple times for a single 'msg'
1241  * iterates through the replies.  The caller must initially leave 'msg''s layer
1242  * pointers null and not modify them between calls.
1243  *
1244  * Returns 0 if successful, EOF if no replies were left in this 'msg',
1245  * otherwise a positive errno value. */
1246 int
1247 ofputil_decode_flow_stats_reply(struct ofputil_flow_stats *fs,
1248                                 struct ofpbuf *msg,
1249                                 enum nx_flow_format flow_format)
1250 {
1251     const struct ofputil_msg_type *type;
1252     int code;
1253
1254     ofputil_decode_msg_type(msg->l2 ? msg->l2 : msg->data, &type);
1255     code = ofputil_msg_type_code(type);
1256     if (!msg->l2) {
1257         msg->l2 = msg->data;
1258         if (code == OFPUTIL_OFPST_FLOW_REPLY) {
1259             ofpbuf_pull(msg, sizeof(struct ofp_stats_reply));
1260         } else if (code == OFPUTIL_NXST_FLOW_REPLY) {
1261             ofpbuf_pull(msg, sizeof(struct nicira_stats_msg));
1262         } else {
1263             NOT_REACHED();
1264         }
1265     }
1266
1267     if (!msg->size) {
1268         return EOF;
1269     } else if (code == OFPUTIL_OFPST_FLOW_REPLY) {
1270         const struct ofp_flow_stats *ofs;
1271         size_t length;
1272
1273         ofs = ofpbuf_try_pull(msg, sizeof *ofs);
1274         if (!ofs) {
1275             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply has %zu leftover "
1276                          "bytes at end", msg->size);
1277             return EINVAL;
1278         }
1279
1280         length = ntohs(ofs->length);
1281         if (length < sizeof *ofs) {
1282             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply claims invalid "
1283                          "length %zu", length);
1284             return EINVAL;
1285         }
1286
1287         if (ofputil_pull_actions(msg, length - sizeof *ofs,
1288                                  &fs->actions, &fs->n_actions)) {
1289             return EINVAL;
1290         }
1291
1292         fs->cookie = get_32aligned_be64(&ofs->cookie);
1293         ofputil_cls_rule_from_match(&ofs->match, ntohs(ofs->priority),
1294                                     flow_format, fs->cookie, &fs->rule);
1295         fs->table_id = ofs->table_id;
1296         fs->duration_sec = ntohl(ofs->duration_sec);
1297         fs->duration_nsec = ntohl(ofs->duration_nsec);
1298         fs->idle_timeout = ntohs(ofs->idle_timeout);
1299         fs->hard_timeout = ntohs(ofs->hard_timeout);
1300         fs->packet_count = ntohll(get_32aligned_be64(&ofs->packet_count));
1301         fs->byte_count = ntohll(get_32aligned_be64(&ofs->byte_count));
1302     } else if (code == OFPUTIL_NXST_FLOW_REPLY) {
1303         const struct nx_flow_stats *nfs;
1304         size_t match_len, length;
1305
1306         nfs = ofpbuf_try_pull(msg, sizeof *nfs);
1307         if (!nfs) {
1308             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply has %zu leftover "
1309                          "bytes at end", msg->size);
1310             return EINVAL;
1311         }
1312
1313         length = ntohs(nfs->length);
1314         match_len = ntohs(nfs->match_len);
1315         if (length < sizeof *nfs + ROUND_UP(match_len, 8)) {
1316             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply with match_len=%zu "
1317                          "claims invalid length %zu", match_len, length);
1318             return EINVAL;
1319         }
1320         if (nx_pull_match(msg, match_len, ntohs(nfs->priority), &fs->rule)) {
1321             return EINVAL;
1322         }
1323
1324         if (ofputil_pull_actions(msg,
1325                                  length - sizeof *nfs - ROUND_UP(match_len, 8),
1326                                  &fs->actions, &fs->n_actions)) {
1327             return EINVAL;
1328         }
1329
1330         fs->cookie = nfs->cookie;
1331         fs->table_id = nfs->table_id;
1332         fs->duration_sec = ntohl(nfs->duration_sec);
1333         fs->duration_nsec = ntohl(nfs->duration_nsec);
1334         fs->idle_timeout = ntohs(nfs->idle_timeout);
1335         fs->hard_timeout = ntohs(nfs->hard_timeout);
1336         fs->packet_count = ntohll(nfs->packet_count);
1337         fs->byte_count = ntohll(nfs->byte_count);
1338     } else {
1339         NOT_REACHED();
1340     }
1341
1342     return 0;
1343 }
1344
1345 /* Converts an OFPT_FLOW_REMOVED or NXT_FLOW_REMOVED message 'oh', received
1346  * when the current flow format was 'flow_format', into an abstract
1347  * ofputil_flow_removed in 'fr'.  Returns 0 if successful, otherwise an
1348  * OpenFlow error code.
1349  *
1350  * For OFPT_FLOW_REMOVED messages, 'flow_format' should be the current flow
1351  * format at the time when the message was received.  Otherwise 'flow_format'
1352  * is ignored. */
1353 int
1354 ofputil_decode_flow_removed(struct ofputil_flow_removed *fr,
1355                             const struct ofp_header *oh,
1356                             enum nx_flow_format flow_format)
1357 {
1358     const struct ofputil_msg_type *type;
1359     enum ofputil_msg_code code;
1360
1361     ofputil_decode_msg_type(oh, &type);
1362     code = ofputil_msg_type_code(type);
1363     if (code == OFPUTIL_OFPT_FLOW_REMOVED) {
1364         const struct ofp_flow_removed *ofr;
1365
1366         ofr = (const struct ofp_flow_removed *) oh;
1367         ofputil_cls_rule_from_match(&ofr->match, ntohs(ofr->priority),
1368                                     flow_format, ofr->cookie, &fr->rule);
1369         fr->cookie = ofr->cookie;
1370         fr->reason = ofr->reason;
1371         fr->duration_sec = ntohl(ofr->duration_sec);
1372         fr->duration_nsec = ntohl(ofr->duration_nsec);
1373         fr->idle_timeout = ntohs(ofr->idle_timeout);
1374         fr->packet_count = ntohll(ofr->packet_count);
1375         fr->byte_count = ntohll(ofr->byte_count);
1376     } else if (code == OFPUTIL_NXT_FLOW_REMOVED) {
1377         struct nx_flow_removed *nfr;
1378         struct ofpbuf b;
1379         int error;
1380
1381         ofpbuf_use_const(&b, oh, ntohs(oh->length));
1382
1383         nfr = ofpbuf_pull(&b, sizeof *nfr);
1384         error = nx_pull_match(&b, ntohs(nfr->match_len), ntohs(nfr->priority),
1385                               &fr->rule);
1386         if (error) {
1387             return error;
1388         }
1389         if (b.size) {
1390             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
1391         }
1392
1393         fr->cookie = nfr->cookie;
1394         fr->reason = nfr->reason;
1395         fr->duration_sec = ntohl(nfr->duration_sec);
1396         fr->duration_nsec = ntohl(nfr->duration_nsec);
1397         fr->idle_timeout = ntohs(nfr->idle_timeout);
1398         fr->packet_count = ntohll(nfr->packet_count);
1399         fr->byte_count = ntohll(nfr->byte_count);
1400     } else {
1401         NOT_REACHED();
1402     }
1403
1404     return 0;
1405 }
1406
1407 /* Converts abstract ofputil_flow_removed 'fr' into an OFPT_FLOW_REMOVED or
1408  * NXT_FLOW_REMOVED message 'oh' according to 'flow_format', and returns the
1409  * message. */
1410 struct ofpbuf *
1411 ofputil_encode_flow_removed(const struct ofputil_flow_removed *fr,
1412                             enum nx_flow_format flow_format)
1413 {
1414     struct ofpbuf *msg;
1415
1416     if (flow_format == NXFF_OPENFLOW10
1417         || flow_format == NXFF_TUN_ID_FROM_COOKIE) {
1418         struct ofp_flow_removed *ofr;
1419
1420         ofr = make_openflow_xid(sizeof *ofr, OFPT_FLOW_REMOVED, htonl(0),
1421                                 &msg);
1422         ofputil_cls_rule_to_match(&fr->rule, flow_format, &ofr->match,
1423                                   fr->cookie, &ofr->cookie);
1424         ofr->priority = htons(fr->rule.priority);
1425         ofr->reason = fr->reason;
1426         ofr->duration_sec = htonl(fr->duration_sec);
1427         ofr->duration_nsec = htonl(fr->duration_nsec);
1428         ofr->idle_timeout = htons(fr->idle_timeout);
1429         ofr->packet_count = htonll(fr->packet_count);
1430         ofr->byte_count = htonll(fr->byte_count);
1431     } else if (flow_format == NXFF_NXM) {
1432         struct nx_flow_removed *nfr;
1433         int match_len;
1434
1435         make_nxmsg_xid(sizeof *nfr, NXT_FLOW_REMOVED, htonl(0), &msg);
1436         match_len = nx_put_match(msg, &fr->rule);
1437
1438         nfr = msg->data;
1439         nfr->cookie = fr->cookie;
1440         nfr->priority = htons(fr->rule.priority);
1441         nfr->reason = fr->reason;
1442         nfr->duration_sec = htonl(fr->duration_sec);
1443         nfr->duration_nsec = htonl(fr->duration_nsec);
1444         nfr->idle_timeout = htons(fr->idle_timeout);
1445         nfr->match_len = htons(match_len);
1446         nfr->packet_count = htonll(fr->packet_count);
1447         nfr->byte_count = htonll(fr->byte_count);
1448     } else {
1449         NOT_REACHED();
1450     }
1451
1452     return msg;
1453 }
1454
1455 /* Converts abstract ofputil_packet_in 'pin' into an OFPT_PACKET_IN message
1456  * and returns the message.
1457  *
1458  * If 'rw_packet' is NULL, the caller takes ownership of the newly allocated
1459  * returned ofpbuf.
1460  *
1461  * If 'rw_packet' is nonnull, then it must contain the same data as
1462  * pin->packet.  'rw_packet' is allowed to be the same ofpbuf as pin->packet.
1463  * It is modified in-place into an OFPT_PACKET_IN message according to 'pin',
1464  * and then ofputil_encode_packet_in() returns 'rw_packet'.  If 'rw_packet' has
1465  * enough headroom to insert a "struct ofp_packet_in", this is more efficient
1466  * than ofputil_encode_packet_in() because it does not copy the packet
1467  * payload. */
1468 struct ofpbuf *
1469 ofputil_encode_packet_in(const struct ofputil_packet_in *pin,
1470                         struct ofpbuf *rw_packet)
1471 {
1472     int total_len = pin->packet->size;
1473     struct ofp_packet_in *opi;
1474
1475     if (rw_packet) {
1476         if (pin->send_len < rw_packet->size) {
1477             rw_packet->size = pin->send_len;
1478         }
1479     } else {
1480         rw_packet = ofpbuf_clone_data_with_headroom(
1481             pin->packet->data, MIN(pin->send_len, pin->packet->size),
1482             offsetof(struct ofp_packet_in, data));
1483     }
1484
1485     /* Add OFPT_PACKET_IN. */
1486     opi = ofpbuf_push_zeros(rw_packet, offsetof(struct ofp_packet_in, data));
1487     opi->header.version = OFP_VERSION;
1488     opi->header.type = OFPT_PACKET_IN;
1489     opi->total_len = htons(total_len);
1490     opi->in_port = htons(pin->in_port);
1491     opi->reason = pin->reason;
1492     opi->buffer_id = htonl(pin->buffer_id);
1493     update_openflow_length(rw_packet);
1494
1495     return rw_packet;
1496 }
1497
1498 /* Returns a string representing the message type of 'type'.  The string is the
1499  * enumeration constant for the type, e.g. "OFPT_HELLO".  For statistics
1500  * messages, the constant is followed by "request" or "reply",
1501  * e.g. "OFPST_AGGREGATE reply". */
1502 const char *
1503 ofputil_msg_type_name(const struct ofputil_msg_type *type)
1504 {
1505     return type->name;
1506 }
1507 \f
1508 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
1509  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
1510  * an arbitrary transaction id.  Allocated bytes beyond the header, if any, are
1511  * zeroed.
1512  *
1513  * The caller is responsible for freeing '*bufferp' when it is no longer
1514  * needed.
1515  *
1516  * The OpenFlow header length is initially set to 'openflow_len'; if the
1517  * message is later extended, the length should be updated with
1518  * update_openflow_length() before sending.
1519  *
1520  * Returns the header. */
1521 void *
1522 make_openflow(size_t openflow_len, uint8_t type, struct ofpbuf **bufferp)
1523 {
1524     *bufferp = ofpbuf_new(openflow_len);
1525     return put_openflow_xid(openflow_len, type, alloc_xid(), *bufferp);
1526 }
1527
1528 /* Similar to make_openflow() but creates a Nicira vendor extension message
1529  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1530 void *
1531 make_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf **bufferp)
1532 {
1533     return make_nxmsg_xid(openflow_len, subtype, alloc_xid(), bufferp);
1534 }
1535
1536 /* Allocates and stores in '*bufferp' a new ofpbuf with a size of
1537  * 'openflow_len', starting with an OpenFlow header with the given 'type' and
1538  * transaction id 'xid'.  Allocated bytes beyond the header, if any, are
1539  * zeroed.
1540  *
1541  * The caller is responsible for freeing '*bufferp' when it is no longer
1542  * needed.
1543  *
1544  * The OpenFlow header length is initially set to 'openflow_len'; if the
1545  * message is later extended, the length should be updated with
1546  * update_openflow_length() before sending.
1547  *
1548  * Returns the header. */
1549 void *
1550 make_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
1551                   struct ofpbuf **bufferp)
1552 {
1553     *bufferp = ofpbuf_new(openflow_len);
1554     return put_openflow_xid(openflow_len, type, xid, *bufferp);
1555 }
1556
1557 /* Similar to make_openflow_xid() but creates a Nicira vendor extension message
1558  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1559 void *
1560 make_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
1561                struct ofpbuf **bufferp)
1562 {
1563     *bufferp = ofpbuf_new(openflow_len);
1564     return put_nxmsg_xid(openflow_len, subtype, xid, *bufferp);
1565 }
1566
1567 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
1568  * with the given 'type' and an arbitrary transaction id.  Allocated bytes
1569  * beyond the header, if any, are zeroed.
1570  *
1571  * The OpenFlow header length is initially set to 'openflow_len'; if the
1572  * message is later extended, the length should be updated with
1573  * update_openflow_length() before sending.
1574  *
1575  * Returns the header. */
1576 void *
1577 put_openflow(size_t openflow_len, uint8_t type, struct ofpbuf *buffer)
1578 {
1579     return put_openflow_xid(openflow_len, type, alloc_xid(), buffer);
1580 }
1581
1582 /* Appends 'openflow_len' bytes to 'buffer', starting with an OpenFlow header
1583  * with the given 'type' and an transaction id 'xid'.  Allocated bytes beyond
1584  * the header, if any, are zeroed.
1585  *
1586  * The OpenFlow header length is initially set to 'openflow_len'; if the
1587  * message is later extended, the length should be updated with
1588  * update_openflow_length() before sending.
1589  *
1590  * Returns the header. */
1591 void *
1592 put_openflow_xid(size_t openflow_len, uint8_t type, ovs_be32 xid,
1593                  struct ofpbuf *buffer)
1594 {
1595     struct ofp_header *oh;
1596
1597     assert(openflow_len >= sizeof *oh);
1598     assert(openflow_len <= UINT16_MAX);
1599
1600     oh = ofpbuf_put_uninit(buffer, openflow_len);
1601     oh->version = OFP_VERSION;
1602     oh->type = type;
1603     oh->length = htons(openflow_len);
1604     oh->xid = xid;
1605     memset(oh + 1, 0, openflow_len - sizeof *oh);
1606     return oh;
1607 }
1608
1609 /* Similar to put_openflow() but append a Nicira vendor extension message with
1610  * the specific 'subtype'.  'subtype' should be in host byte order. */
1611 void *
1612 put_nxmsg(size_t openflow_len, uint32_t subtype, struct ofpbuf *buffer)
1613 {
1614     return put_nxmsg_xid(openflow_len, subtype, alloc_xid(), buffer);
1615 }
1616
1617 /* Similar to put_openflow_xid() but append a Nicira vendor extension message
1618  * with the specific 'subtype'.  'subtype' should be in host byte order. */
1619 void *
1620 put_nxmsg_xid(size_t openflow_len, uint32_t subtype, ovs_be32 xid,
1621               struct ofpbuf *buffer)
1622 {
1623     struct nicira_header *nxh;
1624
1625     nxh = put_openflow_xid(openflow_len, OFPT_VENDOR, xid, buffer);
1626     nxh->vendor = htonl(NX_VENDOR_ID);
1627     nxh->subtype = htonl(subtype);
1628     return nxh;
1629 }
1630
1631 /* Updates the 'length' field of the OpenFlow message in 'buffer' to
1632  * 'buffer->size'. */
1633 void
1634 update_openflow_length(struct ofpbuf *buffer)
1635 {
1636     struct ofp_header *oh = ofpbuf_at_assert(buffer, 0, sizeof *oh);
1637     oh->length = htons(buffer->size);
1638 }
1639
1640 /* Creates an ofp_stats_request with the given 'type' and 'body_len' bytes of
1641  * space allocated for the 'body' member.  Returns the first byte of the 'body'
1642  * member. */
1643 void *
1644 ofputil_make_stats_request(size_t body_len, uint16_t type,
1645                            struct ofpbuf **bufferp)
1646 {
1647     struct ofp_stats_request *osr;
1648     osr = make_openflow((offsetof(struct ofp_stats_request, body)
1649                         + body_len), OFPT_STATS_REQUEST, bufferp);
1650     osr->type = htons(type);
1651     osr->flags = htons(0);
1652     return osr->body;
1653 }
1654
1655 /* Creates a stats request message with Nicira as vendor and the given
1656  * 'subtype', of total length 'openflow_len'.  Returns the message. */
1657 void *
1658 ofputil_make_nxstats_request(size_t openflow_len, uint32_t subtype,
1659                              struct ofpbuf **bufferp)
1660 {
1661     struct nicira_stats_msg *nsm;
1662
1663     nsm = make_openflow(openflow_len, OFPT_STATS_REQUEST, bufferp);
1664     nsm->type = htons(OFPST_VENDOR);
1665     nsm->flags = htons(0);
1666     nsm->vendor = htonl(NX_VENDOR_ID);
1667     nsm->subtype = htonl(subtype);
1668     return nsm;
1669 }
1670
1671 /* Returns the first byte of the 'body' member of the ofp_stats_request or
1672  * ofp_stats_reply in 'oh'. */
1673 const void *
1674 ofputil_stats_body(const struct ofp_header *oh)
1675 {
1676     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1677     return ((const struct ofp_stats_request *) oh)->body;
1678 }
1679
1680 /* Returns the length of the 'body' member of the ofp_stats_request or
1681  * ofp_stats_reply in 'oh'. */
1682 size_t
1683 ofputil_stats_body_len(const struct ofp_header *oh)
1684 {
1685     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1686     return ntohs(oh->length) - sizeof(struct ofp_stats_request);
1687 }
1688
1689 /* Returns the first byte of the body of the nicira_stats_msg in 'oh'. */
1690 const void *
1691 ofputil_nxstats_body(const struct ofp_header *oh)
1692 {
1693     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1694     return ((const struct nicira_stats_msg *) oh) + 1;
1695 }
1696
1697 /* Returns the length of the body of the nicira_stats_msg in 'oh'. */
1698 size_t
1699 ofputil_nxstats_body_len(const struct ofp_header *oh)
1700 {
1701     assert(oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY);
1702     return ntohs(oh->length) - sizeof(struct nicira_stats_msg);
1703 }
1704
1705 struct ofpbuf *
1706 make_flow_mod(uint16_t command, const struct cls_rule *rule,
1707               size_t actions_len)
1708 {
1709     struct ofp_flow_mod *ofm;
1710     size_t size = sizeof *ofm + actions_len;
1711     struct ofpbuf *out = ofpbuf_new(size);
1712     ofm = ofpbuf_put_zeros(out, sizeof *ofm);
1713     ofm->header.version = OFP_VERSION;
1714     ofm->header.type = OFPT_FLOW_MOD;
1715     ofm->header.length = htons(size);
1716     ofm->cookie = 0;
1717     ofm->priority = htons(MIN(rule->priority, UINT16_MAX));
1718     ofputil_cls_rule_to_match(rule, NXFF_OPENFLOW10, &ofm->match, 0, NULL);
1719     ofm->command = htons(command);
1720     return out;
1721 }
1722
1723 struct ofpbuf *
1724 make_add_flow(const struct cls_rule *rule, uint32_t buffer_id,
1725               uint16_t idle_timeout, size_t actions_len)
1726 {
1727     struct ofpbuf *out = make_flow_mod(OFPFC_ADD, rule, actions_len);
1728     struct ofp_flow_mod *ofm = out->data;
1729     ofm->idle_timeout = htons(idle_timeout);
1730     ofm->hard_timeout = htons(OFP_FLOW_PERMANENT);
1731     ofm->buffer_id = htonl(buffer_id);
1732     return out;
1733 }
1734
1735 struct ofpbuf *
1736 make_del_flow(const struct cls_rule *rule)
1737 {
1738     struct ofpbuf *out = make_flow_mod(OFPFC_DELETE_STRICT, rule, 0);
1739     struct ofp_flow_mod *ofm = out->data;
1740     ofm->out_port = htons(OFPP_NONE);
1741     return out;
1742 }
1743
1744 struct ofpbuf *
1745 make_add_simple_flow(const struct cls_rule *rule,
1746                      uint32_t buffer_id, uint16_t out_port,
1747                      uint16_t idle_timeout)
1748 {
1749     if (out_port != OFPP_NONE) {
1750         struct ofp_action_output *oao;
1751         struct ofpbuf *buffer;
1752
1753         buffer = make_add_flow(rule, buffer_id, idle_timeout, sizeof *oao);
1754         oao = ofpbuf_put_zeros(buffer, sizeof *oao);
1755         oao->type = htons(OFPAT_OUTPUT);
1756         oao->len = htons(sizeof *oao);
1757         oao->port = htons(out_port);
1758         return buffer;
1759     } else {
1760         return make_add_flow(rule, buffer_id, idle_timeout, 0);
1761     }
1762 }
1763
1764 struct ofpbuf *
1765 make_packet_in(uint32_t buffer_id, uint16_t in_port, uint8_t reason,
1766                const struct ofpbuf *payload, int max_send_len)
1767 {
1768     struct ofp_packet_in *opi;
1769     struct ofpbuf *buf;
1770     int send_len;
1771
1772     send_len = MIN(max_send_len, payload->size);
1773     buf = ofpbuf_new(sizeof *opi + send_len);
1774     opi = put_openflow_xid(offsetof(struct ofp_packet_in, data),
1775                            OFPT_PACKET_IN, 0, buf);
1776     opi->buffer_id = htonl(buffer_id);
1777     opi->total_len = htons(payload->size);
1778     opi->in_port = htons(in_port);
1779     opi->reason = reason;
1780     ofpbuf_put(buf, payload->data, send_len);
1781     update_openflow_length(buf);
1782
1783     return buf;
1784 }
1785
1786 struct ofpbuf *
1787 make_packet_out(const struct ofpbuf *packet, uint32_t buffer_id,
1788                 uint16_t in_port,
1789                 const struct ofp_action_header *actions, size_t n_actions)
1790 {
1791     size_t actions_len = n_actions * sizeof *actions;
1792     struct ofp_packet_out *opo;
1793     size_t size = sizeof *opo + actions_len + (packet ? packet->size : 0);
1794     struct ofpbuf *out = ofpbuf_new(size);
1795
1796     opo = ofpbuf_put_uninit(out, sizeof *opo);
1797     opo->header.version = OFP_VERSION;
1798     opo->header.type = OFPT_PACKET_OUT;
1799     opo->header.length = htons(size);
1800     opo->header.xid = htonl(0);
1801     opo->buffer_id = htonl(buffer_id);
1802     opo->in_port = htons(in_port == ODPP_LOCAL ? OFPP_LOCAL : in_port);
1803     opo->actions_len = htons(actions_len);
1804     ofpbuf_put(out, actions, actions_len);
1805     if (packet) {
1806         ofpbuf_put(out, packet->data, packet->size);
1807     }
1808     return out;
1809 }
1810
1811 struct ofpbuf *
1812 make_unbuffered_packet_out(const struct ofpbuf *packet,
1813                            uint16_t in_port, uint16_t out_port)
1814 {
1815     struct ofp_action_output action;
1816     action.type = htons(OFPAT_OUTPUT);
1817     action.len = htons(sizeof action);
1818     action.port = htons(out_port);
1819     return make_packet_out(packet, UINT32_MAX, in_port,
1820                            (struct ofp_action_header *) &action, 1);
1821 }
1822
1823 struct ofpbuf *
1824 make_buffered_packet_out(uint32_t buffer_id,
1825                          uint16_t in_port, uint16_t out_port)
1826 {
1827     if (out_port != OFPP_NONE) {
1828         struct ofp_action_output action;
1829         action.type = htons(OFPAT_OUTPUT);
1830         action.len = htons(sizeof action);
1831         action.port = htons(out_port);
1832         return make_packet_out(NULL, buffer_id, in_port,
1833                                (struct ofp_action_header *) &action, 1);
1834     } else {
1835         return make_packet_out(NULL, buffer_id, in_port, NULL, 0);
1836     }
1837 }
1838
1839 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
1840 struct ofpbuf *
1841 make_echo_request(void)
1842 {
1843     struct ofp_header *rq;
1844     struct ofpbuf *out = ofpbuf_new(sizeof *rq);
1845     rq = ofpbuf_put_uninit(out, sizeof *rq);
1846     rq->version = OFP_VERSION;
1847     rq->type = OFPT_ECHO_REQUEST;
1848     rq->length = htons(sizeof *rq);
1849     rq->xid = htonl(0);
1850     return out;
1851 }
1852
1853 /* Creates and returns an OFPT_ECHO_REPLY message matching the
1854  * OFPT_ECHO_REQUEST message in 'rq'. */
1855 struct ofpbuf *
1856 make_echo_reply(const struct ofp_header *rq)
1857 {
1858     size_t size = ntohs(rq->length);
1859     struct ofpbuf *out = ofpbuf_new(size);
1860     struct ofp_header *reply = ofpbuf_put(out, rq, size);
1861     reply->type = OFPT_ECHO_REPLY;
1862     return out;
1863 }
1864
1865 static int
1866 check_action_exact_len(const union ofp_action *a, unsigned int len,
1867                        unsigned int required_len)
1868 {
1869     if (len != required_len) {
1870         VLOG_WARN_RL(&bad_ofmsg_rl, "action %"PRIu16" has invalid length "
1871                      "%"PRIu16" (must be %u)\n",
1872                      ntohs(a->type), ntohs(a->header.len), required_len);
1873         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1874     }
1875     return 0;
1876 }
1877
1878 static int
1879 check_nx_action_exact_len(const struct nx_action_header *a,
1880                           unsigned int len, unsigned int required_len)
1881 {
1882     if (len != required_len) {
1883         VLOG_WARN_RL(&bad_ofmsg_rl,
1884                      "Nicira action %"PRIu16" has invalid length %"PRIu16" "
1885                      "(must be %u)\n",
1886                      ntohs(a->subtype), ntohs(a->len), required_len);
1887         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1888     }
1889     return 0;
1890 }
1891
1892 /* Checks that 'port' is a valid output port for the OFPAT_OUTPUT action, given
1893  * that the switch will never have more than 'max_ports' ports.  Returns 0 if
1894  * 'port' is valid, otherwise an ofp_mkerr() return code. */
1895 static int
1896 check_output_port(uint16_t port, int max_ports)
1897 {
1898     switch (port) {
1899     case OFPP_IN_PORT:
1900     case OFPP_TABLE:
1901     case OFPP_NORMAL:
1902     case OFPP_FLOOD:
1903     case OFPP_ALL:
1904     case OFPP_CONTROLLER:
1905     case OFPP_LOCAL:
1906         return 0;
1907
1908     default:
1909         if (port < max_ports) {
1910             return 0;
1911         }
1912         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown output port %x", port);
1913         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
1914     }
1915 }
1916
1917 /* Checks that 'action' is a valid OFPAT_ENQUEUE action, given that the switch
1918  * will never have more than 'max_ports' ports.  Returns 0 if 'port' is valid,
1919  * otherwise an ofp_mkerr() return code. */
1920 static int
1921 check_enqueue_action(const union ofp_action *a, unsigned int len,
1922                      int max_ports)
1923 {
1924     const struct ofp_action_enqueue *oae;
1925     uint16_t port;
1926     int error;
1927
1928     error = check_action_exact_len(a, len, 16);
1929     if (error) {
1930         return error;
1931     }
1932
1933     oae = (const struct ofp_action_enqueue *) a;
1934     port = ntohs(oae->port);
1935     if (port < max_ports || port == OFPP_IN_PORT) {
1936         return 0;
1937     }
1938     VLOG_WARN_RL(&bad_ofmsg_rl, "unknown enqueue port %x", port);
1939     return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_OUT_PORT);
1940 }
1941
1942 static int
1943 check_nicira_action(const union ofp_action *a, unsigned int len,
1944                     const struct flow *flow)
1945 {
1946     const struct nx_action_header *nah;
1947     int subtype;
1948     int error;
1949
1950     if (len < 16) {
1951         VLOG_WARN_RL(&bad_ofmsg_rl,
1952                      "Nicira vendor action only %u bytes", len);
1953         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
1954     }
1955     nah = (const struct nx_action_header *) a;
1956
1957     subtype = ntohs(nah->subtype);
1958     if (subtype > TYPE_MAXIMUM(enum nx_action_subtype)) {
1959         /* This is necessary because enum nx_action_subtype may be an
1960          * 8-bit type, so the cast below throws away the top 8 bits. */
1961         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR_TYPE);
1962     }
1963
1964     switch ((enum nx_action_subtype) subtype) {
1965     case NXAST_RESUBMIT:
1966     case NXAST_SET_TUNNEL:
1967     case NXAST_DROP_SPOOFED_ARP:
1968     case NXAST_SET_QUEUE:
1969     case NXAST_POP_QUEUE:
1970         return check_nx_action_exact_len(nah, len, 16);
1971
1972     case NXAST_REG_MOVE:
1973         error = check_nx_action_exact_len(nah, len,
1974                                           sizeof(struct nx_action_reg_move));
1975         if (error) {
1976             return error;
1977         }
1978         return nxm_check_reg_move((const struct nx_action_reg_move *) a, flow);
1979
1980     case NXAST_REG_LOAD:
1981         error = check_nx_action_exact_len(nah, len,
1982                                           sizeof(struct nx_action_reg_load));
1983         if (error) {
1984             return error;
1985         }
1986         return nxm_check_reg_load((const struct nx_action_reg_load *) a, flow);
1987
1988     case NXAST_NOTE:
1989         return 0;
1990
1991     case NXAST_SET_TUNNEL64:
1992         return check_nx_action_exact_len(
1993             nah, len, sizeof(struct nx_action_set_tunnel64));
1994
1995     case NXAST_MULTIPATH:
1996         error = check_nx_action_exact_len(
1997             nah, len, sizeof(struct nx_action_multipath));
1998         if (error) {
1999             return error;
2000         }
2001         return multipath_check((const struct nx_action_multipath *) a);
2002
2003     case NXAST_AUTOPATH:
2004         error = check_nx_action_exact_len(
2005             nah, len, sizeof(struct nx_action_autopath));
2006         if (error) {
2007             return error;
2008         }
2009         return autopath_check((const struct nx_action_autopath *) a);
2010
2011     case NXAST_SNAT__OBSOLETE:
2012     default:
2013         VLOG_WARN_RL(&bad_ofmsg_rl,
2014                      "unknown Nicira vendor action subtype %d", subtype);
2015         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR_TYPE);
2016     }
2017 }
2018
2019 static int
2020 check_action(const union ofp_action *a, unsigned int len,
2021              const struct flow *flow, int max_ports)
2022 {
2023     enum ofp_action_type type = ntohs(a->type);
2024     int error;
2025
2026     switch (type) {
2027     case OFPAT_OUTPUT:
2028         error = check_action_exact_len(a, len, 8);
2029         if (error) {
2030             return error;
2031         }
2032         return check_output_port(ntohs(a->output.port), max_ports);
2033
2034     case OFPAT_SET_VLAN_VID:
2035         error = check_action_exact_len(a, len, 8);
2036         if (error) {
2037             return error;
2038         }
2039         if (a->vlan_vid.vlan_vid & ~htons(0xfff)) {
2040             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
2041         }
2042         return 0;
2043
2044     case OFPAT_SET_VLAN_PCP:
2045         error = check_action_exact_len(a, len, 8);
2046         if (error) {
2047             return error;
2048         }
2049         if (a->vlan_vid.vlan_vid & ~7) {
2050             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_ARGUMENT);
2051         }
2052         return 0;
2053
2054     case OFPAT_STRIP_VLAN:
2055     case OFPAT_SET_NW_SRC:
2056     case OFPAT_SET_NW_DST:
2057     case OFPAT_SET_NW_TOS:
2058     case OFPAT_SET_TP_SRC:
2059     case OFPAT_SET_TP_DST:
2060         return check_action_exact_len(a, len, 8);
2061
2062     case OFPAT_SET_DL_SRC:
2063     case OFPAT_SET_DL_DST:
2064         return check_action_exact_len(a, len, 16);
2065
2066     case OFPAT_VENDOR:
2067         return (a->vendor.vendor == htonl(NX_VENDOR_ID)
2068                 ? check_nicira_action(a, len, flow)
2069                 : ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_VENDOR));
2070
2071     case OFPAT_ENQUEUE:
2072         return check_enqueue_action(a, len, max_ports);
2073
2074     default:
2075         VLOG_WARN_RL(&bad_ofmsg_rl, "unknown action type %d", (int) type);
2076         return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_TYPE);
2077     }
2078 }
2079
2080 int
2081 validate_actions(const union ofp_action *actions, size_t n_actions,
2082                  const struct flow *flow, int max_ports)
2083 {
2084     size_t i;
2085
2086     for (i = 0; i < n_actions; ) {
2087         const union ofp_action *a = &actions[i];
2088         unsigned int len = ntohs(a->header.len);
2089         unsigned int n_slots = len / OFP_ACTION_ALIGN;
2090         unsigned int slots_left = &actions[n_actions] - a;
2091         int error;
2092
2093         if (n_slots > slots_left) {
2094             VLOG_WARN_RL(&bad_ofmsg_rl,
2095                          "action requires %u slots but only %u remain",
2096                          n_slots, slots_left);
2097             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
2098         } else if (!len) {
2099             VLOG_WARN_RL(&bad_ofmsg_rl, "action has invalid length 0");
2100             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
2101         } else if (len % OFP_ACTION_ALIGN) {
2102             VLOG_WARN_RL(&bad_ofmsg_rl, "action length %u is not a multiple "
2103                          "of %d", len, OFP_ACTION_ALIGN);
2104             return ofp_mkerr(OFPET_BAD_ACTION, OFPBAC_BAD_LEN);
2105         }
2106
2107         error = check_action(a, len, flow, max_ports);
2108         if (error) {
2109             return error;
2110         }
2111         i += n_slots;
2112     }
2113     return 0;
2114 }
2115
2116 /* Returns true if 'action' outputs to 'port', false otherwise. */
2117 bool
2118 action_outputs_to_port(const union ofp_action *action, ovs_be16 port)
2119 {
2120     switch (ntohs(action->type)) {
2121     case OFPAT_OUTPUT:
2122         return action->output.port == port;
2123     case OFPAT_ENQUEUE:
2124         return ((const struct ofp_action_enqueue *) action)->port == port;
2125     default:
2126         return false;
2127     }
2128 }
2129
2130 /* The set of actions must either come from a trusted source or have been
2131  * previously validated with validate_actions(). */
2132 const union ofp_action *
2133 actions_first(struct actions_iterator *iter,
2134               const union ofp_action *oa, size_t n_actions)
2135 {
2136     iter->pos = oa;
2137     iter->end = oa + n_actions;
2138     return actions_next(iter);
2139 }
2140
2141 const union ofp_action *
2142 actions_next(struct actions_iterator *iter)
2143 {
2144     if (iter->pos != iter->end) {
2145         const union ofp_action *a = iter->pos;
2146         unsigned int len = ntohs(a->header.len);
2147         iter->pos += len / OFP_ACTION_ALIGN;
2148         return a;
2149     } else {
2150         return NULL;
2151     }
2152 }
2153
2154 void
2155 normalize_match(struct ofp_match *m)
2156 {
2157     enum { OFPFW_NW = (OFPFW_NW_SRC_MASK | OFPFW_NW_DST_MASK | OFPFW_NW_PROTO
2158                        | OFPFW_NW_TOS) };
2159     enum { OFPFW_TP = OFPFW_TP_SRC | OFPFW_TP_DST };
2160     uint32_t wc;
2161
2162     wc = ntohl(m->wildcards) & OVSFW_ALL;
2163     if (wc & OFPFW_DL_TYPE) {
2164         m->dl_type = 0;
2165
2166         /* Can't sensibly match on network or transport headers if the
2167          * data link type is unknown. */
2168         wc |= OFPFW_NW | OFPFW_TP;
2169         m->nw_src = m->nw_dst = m->nw_proto = m->nw_tos = 0;
2170         m->tp_src = m->tp_dst = 0;
2171     } else if (m->dl_type == htons(ETH_TYPE_IP)) {
2172         if (wc & OFPFW_NW_PROTO) {
2173             m->nw_proto = 0;
2174
2175             /* Can't sensibly match on transport headers if the network
2176              * protocol is unknown. */
2177             wc |= OFPFW_TP;
2178             m->tp_src = m->tp_dst = 0;
2179         } else if (m->nw_proto == IPPROTO_TCP ||
2180                    m->nw_proto == IPPROTO_UDP ||
2181                    m->nw_proto == IPPROTO_ICMP) {
2182             if (wc & OFPFW_TP_SRC) {
2183                 m->tp_src = 0;
2184             }
2185             if (wc & OFPFW_TP_DST) {
2186                 m->tp_dst = 0;
2187             }
2188         } else {
2189             /* Transport layer fields will always be extracted as zeros, so we
2190              * can do an exact-match on those values.  */
2191             wc &= ~OFPFW_TP;
2192             m->tp_src = m->tp_dst = 0;
2193         }
2194         if (wc & OFPFW_NW_SRC_MASK) {
2195             m->nw_src &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_SRC_SHIFT);
2196         }
2197         if (wc & OFPFW_NW_DST_MASK) {
2198             m->nw_dst &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_DST_SHIFT);
2199         }
2200         if (wc & OFPFW_NW_TOS) {
2201             m->nw_tos = 0;
2202         } else {
2203             m->nw_tos &= IP_DSCP_MASK;
2204         }
2205     } else if (m->dl_type == htons(ETH_TYPE_ARP)) {
2206         if (wc & OFPFW_NW_PROTO) {
2207             m->nw_proto = 0;
2208         }
2209         if (wc & OFPFW_NW_SRC_MASK) {
2210             m->nw_src &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_SRC_SHIFT);
2211         }
2212         if (wc & OFPFW_NW_DST_MASK) {
2213             m->nw_dst &= ofputil_wcbits_to_netmask(wc >> OFPFW_NW_DST_SHIFT);
2214         }
2215         m->tp_src = m->tp_dst = m->nw_tos = 0;
2216     } else if (m->dl_type == htons(ETH_TYPE_IPV6)) {
2217         /* Don't normalize IPv6 traffic, since OpenFlow doesn't have a
2218          * way to express it. */
2219     } else {
2220         /* Network and transport layer fields will always be extracted as
2221          * zeros, so we can do an exact-match on those values. */
2222         wc &= ~(OFPFW_NW | OFPFW_TP);
2223         m->nw_proto = m->nw_src = m->nw_dst = m->nw_tos = 0;
2224         m->tp_src = m->tp_dst = 0;
2225     }
2226     if (wc & OFPFW_DL_SRC) {
2227         memset(m->dl_src, 0, sizeof m->dl_src);
2228     }
2229     if (wc & OFPFW_DL_DST) {
2230         memset(m->dl_dst, 0, sizeof m->dl_dst);
2231     }
2232     m->wildcards = htonl(wc);
2233 }
2234
2235 /* Returns a string that describes 'match' in a very literal way, without
2236  * interpreting its contents except in a very basic fashion.  The returned
2237  * string is intended to be fixed-length, so that it is easy to see differences
2238  * between two such strings if one is put above another.  This is useful for
2239  * describing changes made by normalize_match().
2240  *
2241  * The caller must free the returned string (with free()). */
2242 char *
2243 ofp_match_to_literal_string(const struct ofp_match *match)
2244 {
2245     return xasprintf("wildcards=%#10"PRIx32" "
2246                      " in_port=%5"PRId16" "
2247                      " dl_src="ETH_ADDR_FMT" "
2248                      " dl_dst="ETH_ADDR_FMT" "
2249                      " dl_vlan=%5"PRId16" "
2250                      " dl_vlan_pcp=%3"PRId8" "
2251                      " dl_type=%#6"PRIx16" "
2252                      " nw_tos=%#4"PRIx8" "
2253                      " nw_proto=%#4"PRIx16" "
2254                      " nw_src=%#10"PRIx32" "
2255                      " nw_dst=%#10"PRIx32" "
2256                      " tp_src=%5"PRId16" "
2257                      " tp_dst=%5"PRId16,
2258                      ntohl(match->wildcards),
2259                      ntohs(match->in_port),
2260                      ETH_ADDR_ARGS(match->dl_src),
2261                      ETH_ADDR_ARGS(match->dl_dst),
2262                      ntohs(match->dl_vlan),
2263                      match->dl_vlan_pcp,
2264                      ntohs(match->dl_type),
2265                      match->nw_tos,
2266                      match->nw_proto,
2267                      ntohl(match->nw_src),
2268                      ntohl(match->nw_dst),
2269                      ntohs(match->tp_src),
2270                      ntohs(match->tp_dst));
2271 }
2272
2273 static uint32_t
2274 vendor_code_to_id(uint8_t code)
2275 {
2276     switch (code) {
2277 #define OFPUTIL_VENDOR(NAME, VENDOR_ID) case NAME: return VENDOR_ID;
2278         OFPUTIL_VENDORS
2279 #undef OFPUTIL_VENDOR
2280     default:
2281         return UINT32_MAX;
2282     }
2283 }
2284
2285 static int
2286 vendor_id_to_code(uint32_t id)
2287 {
2288     switch (id) {
2289 #define OFPUTIL_VENDOR(NAME, VENDOR_ID) case VENDOR_ID: return NAME;
2290         OFPUTIL_VENDORS
2291 #undef OFPUTIL_VENDOR
2292     default:
2293         return -1;
2294     }
2295 }
2296
2297 /* Creates and returns an OpenFlow message of type OFPT_ERROR with the error
2298  * information taken from 'error', whose encoding must be as described in the
2299  * large comment in ofp-util.h.  If 'oh' is nonnull, then the error will use
2300  * oh->xid as its transaction ID, and it will include up to the first 64 bytes
2301  * of 'oh'.
2302  *
2303  * Returns NULL if 'error' is not an OpenFlow error code. */
2304 struct ofpbuf *
2305 ofputil_encode_error_msg(int error, const struct ofp_header *oh)
2306 {
2307     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2308
2309     struct ofpbuf *buf;
2310     const void *data;
2311     size_t len;
2312     uint8_t vendor;
2313     uint16_t type;
2314     uint16_t code;
2315     ovs_be32 xid;
2316
2317     if (!is_ofp_error(error)) {
2318         /* We format 'error' with strerror() here since it seems likely to be
2319          * a system errno value. */
2320         VLOG_WARN_RL(&rl, "invalid OpenFlow error code %d (%s)",
2321                      error, strerror(error));
2322         return NULL;
2323     }
2324
2325     if (oh) {
2326         xid = oh->xid;
2327         data = oh;
2328         len = ntohs(oh->length);
2329         if (len > 64) {
2330             len = 64;
2331         }
2332     } else {
2333         xid = 0;
2334         data = NULL;
2335         len = 0;
2336     }
2337
2338     vendor = get_ofp_err_vendor(error);
2339     type = get_ofp_err_type(error);
2340     code = get_ofp_err_code(error);
2341     if (vendor == OFPUTIL_VENDOR_OPENFLOW) {
2342         struct ofp_error_msg *oem;
2343
2344         oem = make_openflow_xid(len + sizeof *oem, OFPT_ERROR, xid, &buf);
2345         oem->type = htons(type);
2346         oem->code = htons(code);
2347     } else {
2348         struct ofp_error_msg *oem;
2349         struct nx_vendor_error *nve;
2350         uint32_t vendor_id;
2351
2352         vendor_id = vendor_code_to_id(vendor);
2353         if (vendor_id == UINT32_MAX) {
2354             VLOG_WARN_RL(&rl, "error %x contains invalid vendor code %d",
2355                          error, vendor);
2356             return NULL;
2357         }
2358
2359         oem = make_openflow_xid(len + sizeof *oem + sizeof *nve,
2360                                 OFPT_ERROR, xid, &buf);
2361         oem->type = htons(NXET_VENDOR);
2362         oem->code = htons(NXVC_VENDOR_ERROR);
2363
2364         nve = (struct nx_vendor_error *)oem->data;
2365         nve->vendor = htonl(vendor_id);
2366         nve->type = htons(type);
2367         nve->code = htons(code);
2368     }
2369
2370     if (len) {
2371         buf->size -= len;
2372         ofpbuf_put(buf, data, len);
2373     }
2374
2375     return buf;
2376 }
2377
2378 /* Decodes 'oh', which should be an OpenFlow OFPT_ERROR message, and returns an
2379  * Open vSwitch internal error code in the format described in the large
2380  * comment in ofp-util.h.
2381  *
2382  * If 'payload_ofs' is nonnull, on success '*payload_ofs' is set to the offset
2383  * to the payload starting from 'oh' and on failure it is set to 0. */
2384 int
2385 ofputil_decode_error_msg(const struct ofp_header *oh, size_t *payload_ofs)
2386 {
2387     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2388
2389     const struct ofp_error_msg *oem;
2390     uint16_t type, code;
2391     struct ofpbuf b;
2392     int vendor;
2393
2394     if (payload_ofs) {
2395         *payload_ofs = 0;
2396     }
2397     if (oh->type != OFPT_ERROR) {
2398         return EPROTO;
2399     }
2400
2401     ofpbuf_use_const(&b, oh, ntohs(oh->length));
2402     oem = ofpbuf_try_pull(&b, sizeof *oem);
2403     if (!oem) {
2404         return EPROTO;
2405     }
2406
2407     type = ntohs(oem->type);
2408     code = ntohs(oem->code);
2409     if (type == NXET_VENDOR && code == NXVC_VENDOR_ERROR) {
2410         const struct nx_vendor_error *nve = ofpbuf_try_pull(&b, sizeof *nve);
2411         if (!nve) {
2412             return EPROTO;
2413         }
2414
2415         vendor = vendor_id_to_code(ntohl(nve->vendor));
2416         if (vendor < 0) {
2417             VLOG_WARN_RL(&rl, "error contains unknown vendor ID %#"PRIx32,
2418                          ntohl(nve->vendor));
2419             return EPROTO;
2420         }
2421         type = ntohs(nve->type);
2422         code = ntohs(nve->code);
2423     } else {
2424         vendor = OFPUTIL_VENDOR_OPENFLOW;
2425     }
2426
2427     if (type >= 1024) {
2428         VLOG_WARN_RL(&rl, "error contains type %"PRIu16" greater than "
2429                      "supported maximum value 1023", type);
2430         return EPROTO;
2431     }
2432
2433     if (payload_ofs) {
2434         *payload_ofs = (uint8_t *) b.data - (uint8_t *) oh;
2435     }
2436     return ofp_mkerr_vendor(vendor, type, code);
2437 }
2438
2439 void
2440 ofputil_format_error(struct ds *s, int error)
2441 {
2442     if (is_errno(error)) {
2443         ds_put_cstr(s, strerror(error));
2444     } else {
2445         uint16_t type = get_ofp_err_type(error);
2446         uint16_t code = get_ofp_err_code(error);
2447         const char *type_s = ofp_error_type_to_string(type);
2448         const char *code_s = ofp_error_code_to_string(type, code);
2449
2450         ds_put_format(s, "type ");
2451         if (type_s) {
2452             ds_put_cstr(s, type_s);
2453         } else {
2454             ds_put_format(s, "%"PRIu16, type);
2455         }
2456
2457         ds_put_cstr(s, ", code ");
2458         if (code_s) {
2459             ds_put_cstr(s, code_s);
2460         } else {
2461             ds_put_format(s, "%"PRIu16, code);
2462         }
2463     }
2464 }
2465
2466 char *
2467 ofputil_error_to_string(int error)
2468 {
2469     struct ds s = DS_EMPTY_INITIALIZER;
2470     ofputil_format_error(&s, error);
2471     return ds_steal_cstr(&s);
2472 }
2473
2474 /* Attempts to pull 'actions_len' bytes from the front of 'b'.  Returns 0 if
2475  * successful, otherwise an OpenFlow error.
2476  *
2477  * If successful, the first action is stored in '*actionsp' and the number of
2478  * "union ofp_action" size elements into '*n_actionsp'.  Otherwise NULL and 0
2479  * are stored, respectively.
2480  *
2481  * This function does not check that the actions are valid (the caller should
2482  * do so, with validate_actions()).  The caller is also responsible for making
2483  * sure that 'b->data' is initially aligned appropriately for "union
2484  * ofp_action". */
2485 int
2486 ofputil_pull_actions(struct ofpbuf *b, unsigned int actions_len,
2487                      union ofp_action **actionsp, size_t *n_actionsp)
2488 {
2489     if (actions_len % OFP_ACTION_ALIGN != 0) {
2490         VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
2491                      "is not a multiple of %d", actions_len, OFP_ACTION_ALIGN);
2492         goto error;
2493     }
2494
2495     *actionsp = ofpbuf_try_pull(b, actions_len);
2496     if (*actionsp == NULL) {
2497         VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message actions length %u "
2498                      "exceeds remaining message length (%zu)",
2499                      actions_len, b->size);
2500         goto error;
2501     }
2502
2503     *n_actionsp = actions_len / OFP_ACTION_ALIGN;
2504     return 0;
2505
2506 error:
2507     *actionsp = NULL;
2508     *n_actionsp = 0;
2509     return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
2510 }