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