Support userdata in NXT_PACKET_IN2.
[cascardo/ovs.git] / lib / ofp-util.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "ofp-print.h"
19 #include <ctype.h>
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <sys/types.h>
23 #include <netinet/in.h>
24 #include <netinet/icmp6.h>
25 #include <stdlib.h>
26 #include "bundle.h"
27 #include "byte-order.h"
28 #include "classifier.h"
29 #include "dynamic-string.h"
30 #include "learn.h"
31 #include "meta-flow.h"
32 #include "multipath.h"
33 #include "netdev.h"
34 #include "nx-match.h"
35 #include "id-pool.h"
36 #include "ofp-actions.h"
37 #include "ofp-errors.h"
38 #include "ofp-msgs.h"
39 #include "ofp-prop.h"
40 #include "ofp-util.h"
41 #include "ofpbuf.h"
42 #include "openflow/netronome-ext.h"
43 #include "packets.h"
44 #include "pktbuf.h"
45 #include "random.h"
46 #include "tun-metadata.h"
47 #include "unaligned.h"
48 #include "type-props.h"
49 #include "openvswitch/vlog.h"
50 #include "bitmap.h"
51
52 VLOG_DEFINE_THIS_MODULE(ofp_util);
53
54 /* Rate limit for OpenFlow message parse errors.  These always indicate a bug
55  * in the peer and so there's not much point in showing a lot of them. */
56 static struct vlog_rate_limit bad_ofmsg_rl = VLOG_RATE_LIMIT_INIT(1, 5);
57
58 static enum ofputil_table_vacancy ofputil_decode_table_vacancy(
59     ovs_be32 config, enum ofp_version);
60 static enum ofputil_table_eviction ofputil_decode_table_eviction(
61     ovs_be32 config, enum ofp_version);
62 static ovs_be32 ofputil_encode_table_config(enum ofputil_table_miss,
63                                             enum ofputil_table_eviction,
64                                             enum ofputil_table_vacancy,
65                                             enum ofp_version);
66
67 /* Given the wildcard bit count in the least-significant 6 of 'wcbits', returns
68  * an IP netmask with a 1 in each bit that must match and a 0 in each bit that
69  * is wildcarded.
70  *
71  * The bits in 'wcbits' are in the format used in enum ofp_flow_wildcards: 0
72  * is exact match, 1 ignores the LSB, 2 ignores the 2 least-significant bits,
73  * ..., 32 and higher wildcard the entire field.  This is the *opposite* of the
74  * usual convention where e.g. /24 indicates that 8 bits (not 24 bits) are
75  * wildcarded. */
76 ovs_be32
77 ofputil_wcbits_to_netmask(int wcbits)
78 {
79     wcbits &= 0x3f;
80     return wcbits < 32 ? htonl(~((1u << wcbits) - 1)) : 0;
81 }
82
83 /* Given the IP netmask 'netmask', returns the number of bits of the IP address
84  * that it wildcards, that is, the number of 0-bits in 'netmask', a number
85  * between 0 and 32 inclusive.
86  *
87  * If 'netmask' is not a CIDR netmask (see ip_is_cidr()), the return value will
88  * still be in the valid range but isn't otherwise meaningful. */
89 int
90 ofputil_netmask_to_wcbits(ovs_be32 netmask)
91 {
92     return 32 - ip_count_cidr_bits(netmask);
93 }
94
95 /* Converts the OpenFlow 1.0 wildcards in 'ofpfw' (OFPFW10_*) into a
96  * flow_wildcards in 'wc' for use in struct match.  It is the caller's
97  * responsibility to handle the special case where the flow match's dl_vlan is
98  * set to OFP_VLAN_NONE. */
99 void
100 ofputil_wildcard_from_ofpfw10(uint32_t ofpfw, struct flow_wildcards *wc)
101 {
102     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 35);
103
104     /* Initialize most of wc. */
105     flow_wildcards_init_catchall(wc);
106
107     if (!(ofpfw & OFPFW10_IN_PORT)) {
108         wc->masks.in_port.ofp_port = u16_to_ofp(UINT16_MAX);
109     }
110
111     if (!(ofpfw & OFPFW10_NW_TOS)) {
112         wc->masks.nw_tos |= IP_DSCP_MASK;
113     }
114
115     if (!(ofpfw & OFPFW10_NW_PROTO)) {
116         wc->masks.nw_proto = UINT8_MAX;
117     }
118     wc->masks.nw_src = ofputil_wcbits_to_netmask(ofpfw
119                                                  >> OFPFW10_NW_SRC_SHIFT);
120     wc->masks.nw_dst = ofputil_wcbits_to_netmask(ofpfw
121                                                  >> OFPFW10_NW_DST_SHIFT);
122
123     if (!(ofpfw & OFPFW10_TP_SRC)) {
124         wc->masks.tp_src = OVS_BE16_MAX;
125     }
126     if (!(ofpfw & OFPFW10_TP_DST)) {
127         wc->masks.tp_dst = OVS_BE16_MAX;
128     }
129
130     if (!(ofpfw & OFPFW10_DL_SRC)) {
131         WC_MASK_FIELD(wc, dl_src);
132     }
133     if (!(ofpfw & OFPFW10_DL_DST)) {
134         WC_MASK_FIELD(wc, dl_dst);
135     }
136     if (!(ofpfw & OFPFW10_DL_TYPE)) {
137         wc->masks.dl_type = OVS_BE16_MAX;
138     }
139
140     /* VLAN TCI mask. */
141     if (!(ofpfw & OFPFW10_DL_VLAN_PCP)) {
142         wc->masks.vlan_tci |= htons(VLAN_PCP_MASK | VLAN_CFI);
143     }
144     if (!(ofpfw & OFPFW10_DL_VLAN)) {
145         wc->masks.vlan_tci |= htons(VLAN_VID_MASK | VLAN_CFI);
146     }
147 }
148
149 /* Converts the ofp10_match in 'ofmatch' into a struct match in 'match'. */
150 void
151 ofputil_match_from_ofp10_match(const struct ofp10_match *ofmatch,
152                                struct match *match)
153 {
154     uint32_t ofpfw = ntohl(ofmatch->wildcards) & OFPFW10_ALL;
155
156     /* Initialize match->wc. */
157     memset(&match->flow, 0, sizeof match->flow);
158     ofputil_wildcard_from_ofpfw10(ofpfw, &match->wc);
159
160     /* Initialize most of match->flow. */
161     match->flow.nw_src = ofmatch->nw_src;
162     match->flow.nw_dst = ofmatch->nw_dst;
163     match->flow.in_port.ofp_port = u16_to_ofp(ntohs(ofmatch->in_port));
164     match->flow.dl_type = ofputil_dl_type_from_openflow(ofmatch->dl_type);
165     match->flow.tp_src = ofmatch->tp_src;
166     match->flow.tp_dst = ofmatch->tp_dst;
167     match->flow.dl_src = ofmatch->dl_src;
168     match->flow.dl_dst = ofmatch->dl_dst;
169     match->flow.nw_tos = ofmatch->nw_tos & IP_DSCP_MASK;
170     match->flow.nw_proto = ofmatch->nw_proto;
171
172     /* Translate VLANs. */
173     if (!(ofpfw & OFPFW10_DL_VLAN) &&
174         ofmatch->dl_vlan == htons(OFP10_VLAN_NONE)) {
175         /* Match only packets without 802.1Q header.
176          *
177          * When OFPFW10_DL_VLAN_PCP is wildcarded, this is obviously correct.
178          *
179          * If OFPFW10_DL_VLAN_PCP is matched, the flow match is contradictory,
180          * because we can't have a specific PCP without an 802.1Q header.
181          * However, older versions of OVS treated this as matching packets
182          * withut an 802.1Q header, so we do here too. */
183         match->flow.vlan_tci = htons(0);
184         match->wc.masks.vlan_tci = htons(0xffff);
185     } else {
186         ovs_be16 vid, pcp, tci;
187         uint16_t hpcp;
188
189         vid = ofmatch->dl_vlan & htons(VLAN_VID_MASK);
190         hpcp = (ofmatch->dl_vlan_pcp << VLAN_PCP_SHIFT) & VLAN_PCP_MASK;
191         pcp = htons(hpcp);
192         tci = vid | pcp | htons(VLAN_CFI);
193         match->flow.vlan_tci = tci & match->wc.masks.vlan_tci;
194     }
195
196     /* Clean up. */
197     match_zero_wildcarded_fields(match);
198 }
199
200 /* Convert 'match' into the OpenFlow 1.0 match structure 'ofmatch'. */
201 void
202 ofputil_match_to_ofp10_match(const struct match *match,
203                              struct ofp10_match *ofmatch)
204 {
205     const struct flow_wildcards *wc = &match->wc;
206     uint32_t ofpfw;
207
208     /* Figure out most OpenFlow wildcards. */
209     ofpfw = 0;
210     if (!wc->masks.in_port.ofp_port) {
211         ofpfw |= OFPFW10_IN_PORT;
212     }
213     if (!wc->masks.dl_type) {
214         ofpfw |= OFPFW10_DL_TYPE;
215     }
216     if (!wc->masks.nw_proto) {
217         ofpfw |= OFPFW10_NW_PROTO;
218     }
219     ofpfw |= (ofputil_netmask_to_wcbits(wc->masks.nw_src)
220               << OFPFW10_NW_SRC_SHIFT);
221     ofpfw |= (ofputil_netmask_to_wcbits(wc->masks.nw_dst)
222               << OFPFW10_NW_DST_SHIFT);
223     if (!(wc->masks.nw_tos & IP_DSCP_MASK)) {
224         ofpfw |= OFPFW10_NW_TOS;
225     }
226     if (!wc->masks.tp_src) {
227         ofpfw |= OFPFW10_TP_SRC;
228     }
229     if (!wc->masks.tp_dst) {
230         ofpfw |= OFPFW10_TP_DST;
231     }
232     if (eth_addr_is_zero(wc->masks.dl_src)) {
233         ofpfw |= OFPFW10_DL_SRC;
234     }
235     if (eth_addr_is_zero(wc->masks.dl_dst)) {
236         ofpfw |= OFPFW10_DL_DST;
237     }
238
239     /* Translate VLANs. */
240     ofmatch->dl_vlan = htons(0);
241     ofmatch->dl_vlan_pcp = 0;
242     if (match->wc.masks.vlan_tci == htons(0)) {
243         ofpfw |= OFPFW10_DL_VLAN | OFPFW10_DL_VLAN_PCP;
244     } else if (match->wc.masks.vlan_tci & htons(VLAN_CFI)
245                && !(match->flow.vlan_tci & htons(VLAN_CFI))) {
246         ofmatch->dl_vlan = htons(OFP10_VLAN_NONE);
247     } else {
248         if (!(match->wc.masks.vlan_tci & htons(VLAN_VID_MASK))) {
249             ofpfw |= OFPFW10_DL_VLAN;
250         } else {
251             ofmatch->dl_vlan = htons(vlan_tci_to_vid(match->flow.vlan_tci));
252         }
253
254         if (!(match->wc.masks.vlan_tci & htons(VLAN_PCP_MASK))) {
255             ofpfw |= OFPFW10_DL_VLAN_PCP;
256         } else {
257             ofmatch->dl_vlan_pcp = vlan_tci_to_pcp(match->flow.vlan_tci);
258         }
259     }
260
261     /* Compose most of the match structure. */
262     ofmatch->wildcards = htonl(ofpfw);
263     ofmatch->in_port = htons(ofp_to_u16(match->flow.in_port.ofp_port));
264     ofmatch->dl_src = match->flow.dl_src;
265     ofmatch->dl_dst = match->flow.dl_dst;
266     ofmatch->dl_type = ofputil_dl_type_to_openflow(match->flow.dl_type);
267     ofmatch->nw_src = match->flow.nw_src;
268     ofmatch->nw_dst = match->flow.nw_dst;
269     ofmatch->nw_tos = match->flow.nw_tos & IP_DSCP_MASK;
270     ofmatch->nw_proto = match->flow.nw_proto;
271     ofmatch->tp_src = match->flow.tp_src;
272     ofmatch->tp_dst = match->flow.tp_dst;
273     memset(ofmatch->pad1, '\0', sizeof ofmatch->pad1);
274     memset(ofmatch->pad2, '\0', sizeof ofmatch->pad2);
275 }
276
277 enum ofperr
278 ofputil_pull_ofp11_match(struct ofpbuf *buf, struct match *match,
279                          uint16_t *padded_match_len)
280 {
281     struct ofp11_match_header *omh = buf->data;
282     uint16_t match_len;
283
284     if (buf->size < sizeof *omh) {
285         return OFPERR_OFPBMC_BAD_LEN;
286     }
287
288     match_len = ntohs(omh->length);
289
290     switch (ntohs(omh->type)) {
291     case OFPMT_STANDARD: {
292         struct ofp11_match *om;
293
294         if (match_len != sizeof *om || buf->size < sizeof *om) {
295             return OFPERR_OFPBMC_BAD_LEN;
296         }
297         om = ofpbuf_pull(buf, sizeof *om);
298         if (padded_match_len) {
299             *padded_match_len = match_len;
300         }
301         return ofputil_match_from_ofp11_match(om, match);
302     }
303
304     case OFPMT_OXM:
305         if (padded_match_len) {
306             *padded_match_len = ROUND_UP(match_len, 8);
307         }
308         return oxm_pull_match(buf, match);
309
310     default:
311         return OFPERR_OFPBMC_BAD_TYPE;
312     }
313 }
314
315 /* Converts the ofp11_match in 'ofmatch' into a struct match in 'match'.
316  * Returns 0 if successful, otherwise an OFPERR_* value. */
317 enum ofperr
318 ofputil_match_from_ofp11_match(const struct ofp11_match *ofmatch,
319                                struct match *match)
320 {
321     uint16_t wc = ntohl(ofmatch->wildcards);
322     bool ipv4, arp, rarp;
323
324     match_init_catchall(match);
325
326     if (!(wc & OFPFW11_IN_PORT)) {
327         ofp_port_t ofp_port;
328         enum ofperr error;
329
330         error = ofputil_port_from_ofp11(ofmatch->in_port, &ofp_port);
331         if (error) {
332             return OFPERR_OFPBMC_BAD_VALUE;
333         }
334         match_set_in_port(match, ofp_port);
335     }
336
337     match_set_dl_src_masked(match, ofmatch->dl_src,
338                             eth_addr_invert(ofmatch->dl_src_mask));
339     match_set_dl_dst_masked(match, ofmatch->dl_dst,
340                             eth_addr_invert(ofmatch->dl_dst_mask));
341
342     if (!(wc & OFPFW11_DL_VLAN)) {
343         if (ofmatch->dl_vlan == htons(OFPVID11_NONE)) {
344             /* Match only packets without a VLAN tag. */
345             match->flow.vlan_tci = htons(0);
346             match->wc.masks.vlan_tci = OVS_BE16_MAX;
347         } else {
348             if (ofmatch->dl_vlan == htons(OFPVID11_ANY)) {
349                 /* Match any packet with a VLAN tag regardless of VID. */
350                 match->flow.vlan_tci = htons(VLAN_CFI);
351                 match->wc.masks.vlan_tci = htons(VLAN_CFI);
352             } else if (ntohs(ofmatch->dl_vlan) < 4096) {
353                 /* Match only packets with the specified VLAN VID. */
354                 match->flow.vlan_tci = htons(VLAN_CFI) | ofmatch->dl_vlan;
355                 match->wc.masks.vlan_tci = htons(VLAN_CFI | VLAN_VID_MASK);
356             } else {
357                 /* Invalid VID. */
358                 return OFPERR_OFPBMC_BAD_VALUE;
359             }
360
361             if (!(wc & OFPFW11_DL_VLAN_PCP)) {
362                 if (ofmatch->dl_vlan_pcp <= 7) {
363                     match->flow.vlan_tci |= htons(ofmatch->dl_vlan_pcp
364                                                   << VLAN_PCP_SHIFT);
365                     match->wc.masks.vlan_tci |= htons(VLAN_PCP_MASK);
366                 } else {
367                     /* Invalid PCP. */
368                     return OFPERR_OFPBMC_BAD_VALUE;
369                 }
370             }
371         }
372     }
373
374     if (!(wc & OFPFW11_DL_TYPE)) {
375         match_set_dl_type(match,
376                           ofputil_dl_type_from_openflow(ofmatch->dl_type));
377     }
378
379     ipv4 = match->flow.dl_type == htons(ETH_TYPE_IP);
380     arp = match->flow.dl_type == htons(ETH_TYPE_ARP);
381     rarp = match->flow.dl_type == htons(ETH_TYPE_RARP);
382
383     if (ipv4 && !(wc & OFPFW11_NW_TOS)) {
384         if (ofmatch->nw_tos & ~IP_DSCP_MASK) {
385             /* Invalid TOS. */
386             return OFPERR_OFPBMC_BAD_VALUE;
387         }
388
389         match_set_nw_dscp(match, ofmatch->nw_tos);
390     }
391
392     if (ipv4 || arp || rarp) {
393         if (!(wc & OFPFW11_NW_PROTO)) {
394             match_set_nw_proto(match, ofmatch->nw_proto);
395         }
396         match_set_nw_src_masked(match, ofmatch->nw_src, ~ofmatch->nw_src_mask);
397         match_set_nw_dst_masked(match, ofmatch->nw_dst, ~ofmatch->nw_dst_mask);
398     }
399
400 #define OFPFW11_TP_ALL (OFPFW11_TP_SRC | OFPFW11_TP_DST)
401     if (ipv4 && (wc & OFPFW11_TP_ALL) != OFPFW11_TP_ALL) {
402         switch (match->flow.nw_proto) {
403         case IPPROTO_ICMP:
404             /* "A.2.3 Flow Match Structures" in OF1.1 says:
405              *
406              *    The tp_src and tp_dst fields will be ignored unless the
407              *    network protocol specified is as TCP, UDP or SCTP.
408              *
409              * but I'm pretty sure we should support ICMP too, otherwise
410              * that's a regression from OF1.0. */
411             if (!(wc & OFPFW11_TP_SRC)) {
412                 uint16_t icmp_type = ntohs(ofmatch->tp_src);
413                 if (icmp_type < 0x100) {
414                     match_set_icmp_type(match, icmp_type);
415                 } else {
416                     return OFPERR_OFPBMC_BAD_FIELD;
417                 }
418             }
419             if (!(wc & OFPFW11_TP_DST)) {
420                 uint16_t icmp_code = ntohs(ofmatch->tp_dst);
421                 if (icmp_code < 0x100) {
422                     match_set_icmp_code(match, icmp_code);
423                 } else {
424                     return OFPERR_OFPBMC_BAD_FIELD;
425                 }
426             }
427             break;
428
429         case IPPROTO_TCP:
430         case IPPROTO_UDP:
431         case IPPROTO_SCTP:
432             if (!(wc & (OFPFW11_TP_SRC))) {
433                 match_set_tp_src(match, ofmatch->tp_src);
434             }
435             if (!(wc & (OFPFW11_TP_DST))) {
436                 match_set_tp_dst(match, ofmatch->tp_dst);
437             }
438             break;
439
440         default:
441             /* OF1.1 says explicitly to ignore this. */
442             break;
443         }
444     }
445
446     if (eth_type_mpls(match->flow.dl_type)) {
447         if (!(wc & OFPFW11_MPLS_LABEL)) {
448             match_set_mpls_label(match, 0, ofmatch->mpls_label);
449         }
450         if (!(wc & OFPFW11_MPLS_TC)) {
451             match_set_mpls_tc(match, 0, ofmatch->mpls_tc);
452         }
453     }
454
455     match_set_metadata_masked(match, ofmatch->metadata,
456                               ~ofmatch->metadata_mask);
457
458     return 0;
459 }
460
461 /* Convert 'match' into the OpenFlow 1.1 match structure 'ofmatch'. */
462 void
463 ofputil_match_to_ofp11_match(const struct match *match,
464                              struct ofp11_match *ofmatch)
465 {
466     uint32_t wc = 0;
467
468     memset(ofmatch, 0, sizeof *ofmatch);
469     ofmatch->omh.type = htons(OFPMT_STANDARD);
470     ofmatch->omh.length = htons(OFPMT11_STANDARD_LENGTH);
471
472     if (!match->wc.masks.in_port.ofp_port) {
473         wc |= OFPFW11_IN_PORT;
474     } else {
475         ofmatch->in_port = ofputil_port_to_ofp11(match->flow.in_port.ofp_port);
476     }
477
478     ofmatch->dl_src = match->flow.dl_src;
479     ofmatch->dl_src_mask = eth_addr_invert(match->wc.masks.dl_src);
480     ofmatch->dl_dst = match->flow.dl_dst;
481     ofmatch->dl_dst_mask = eth_addr_invert(match->wc.masks.dl_dst);
482
483     if (match->wc.masks.vlan_tci == htons(0)) {
484         wc |= OFPFW11_DL_VLAN | OFPFW11_DL_VLAN_PCP;
485     } else if (match->wc.masks.vlan_tci & htons(VLAN_CFI)
486                && !(match->flow.vlan_tci & htons(VLAN_CFI))) {
487         ofmatch->dl_vlan = htons(OFPVID11_NONE);
488         wc |= OFPFW11_DL_VLAN_PCP;
489     } else {
490         if (!(match->wc.masks.vlan_tci & htons(VLAN_VID_MASK))) {
491             ofmatch->dl_vlan = htons(OFPVID11_ANY);
492         } else {
493             ofmatch->dl_vlan = htons(vlan_tci_to_vid(match->flow.vlan_tci));
494         }
495
496         if (!(match->wc.masks.vlan_tci & htons(VLAN_PCP_MASK))) {
497             wc |= OFPFW11_DL_VLAN_PCP;
498         } else {
499             ofmatch->dl_vlan_pcp = vlan_tci_to_pcp(match->flow.vlan_tci);
500         }
501     }
502
503     if (!match->wc.masks.dl_type) {
504         wc |= OFPFW11_DL_TYPE;
505     } else {
506         ofmatch->dl_type = ofputil_dl_type_to_openflow(match->flow.dl_type);
507     }
508
509     if (!(match->wc.masks.nw_tos & IP_DSCP_MASK)) {
510         wc |= OFPFW11_NW_TOS;
511     } else {
512         ofmatch->nw_tos = match->flow.nw_tos & IP_DSCP_MASK;
513     }
514
515     if (!match->wc.masks.nw_proto) {
516         wc |= OFPFW11_NW_PROTO;
517     } else {
518         ofmatch->nw_proto = match->flow.nw_proto;
519     }
520
521     ofmatch->nw_src = match->flow.nw_src;
522     ofmatch->nw_src_mask = ~match->wc.masks.nw_src;
523     ofmatch->nw_dst = match->flow.nw_dst;
524     ofmatch->nw_dst_mask = ~match->wc.masks.nw_dst;
525
526     if (!match->wc.masks.tp_src) {
527         wc |= OFPFW11_TP_SRC;
528     } else {
529         ofmatch->tp_src = match->flow.tp_src;
530     }
531
532     if (!match->wc.masks.tp_dst) {
533         wc |= OFPFW11_TP_DST;
534     } else {
535         ofmatch->tp_dst = match->flow.tp_dst;
536     }
537
538     if (!(match->wc.masks.mpls_lse[0] & htonl(MPLS_LABEL_MASK))) {
539         wc |= OFPFW11_MPLS_LABEL;
540     } else {
541         ofmatch->mpls_label = htonl(mpls_lse_to_label(
542                                         match->flow.mpls_lse[0]));
543     }
544
545     if (!(match->wc.masks.mpls_lse[0] & htonl(MPLS_TC_MASK))) {
546         wc |= OFPFW11_MPLS_TC;
547     } else {
548         ofmatch->mpls_tc = mpls_lse_to_tc(match->flow.mpls_lse[0]);
549     }
550
551     ofmatch->metadata = match->flow.metadata;
552     ofmatch->metadata_mask = ~match->wc.masks.metadata;
553
554     ofmatch->wildcards = htonl(wc);
555 }
556
557 /* Returns the "typical" length of a match for 'protocol', for use in
558  * estimating space to preallocate. */
559 int
560 ofputil_match_typical_len(enum ofputil_protocol protocol)
561 {
562     switch (protocol) {
563     case OFPUTIL_P_OF10_STD:
564     case OFPUTIL_P_OF10_STD_TID:
565         return sizeof(struct ofp10_match);
566
567     case OFPUTIL_P_OF10_NXM:
568     case OFPUTIL_P_OF10_NXM_TID:
569         return NXM_TYPICAL_LEN;
570
571     case OFPUTIL_P_OF11_STD:
572         return sizeof(struct ofp11_match);
573
574     case OFPUTIL_P_OF12_OXM:
575     case OFPUTIL_P_OF13_OXM:
576     case OFPUTIL_P_OF14_OXM:
577     case OFPUTIL_P_OF15_OXM:
578         return NXM_TYPICAL_LEN;
579
580     default:
581         OVS_NOT_REACHED();
582     }
583 }
584
585 /* Appends to 'b' an struct ofp11_match_header followed by a match that
586  * expresses 'match' properly for 'protocol', plus enough zero bytes to pad the
587  * data appended out to a multiple of 8.  'protocol' must be one that is usable
588  * in OpenFlow 1.1 or later.
589  *
590  * This function can cause 'b''s data to be reallocated.
591  *
592  * Returns the number of bytes appended to 'b', excluding the padding.  Never
593  * returns zero. */
594 int
595 ofputil_put_ofp11_match(struct ofpbuf *b, const struct match *match,
596                         enum ofputil_protocol protocol)
597 {
598     switch (protocol) {
599     case OFPUTIL_P_OF10_STD:
600     case OFPUTIL_P_OF10_STD_TID:
601     case OFPUTIL_P_OF10_NXM:
602     case OFPUTIL_P_OF10_NXM_TID:
603         OVS_NOT_REACHED();
604
605     case OFPUTIL_P_OF11_STD: {
606         struct ofp11_match *om;
607
608         /* Make sure that no padding is needed. */
609         BUILD_ASSERT_DECL(sizeof *om % 8 == 0);
610
611         om = ofpbuf_put_uninit(b, sizeof *om);
612         ofputil_match_to_ofp11_match(match, om);
613         return sizeof *om;
614     }
615
616     case OFPUTIL_P_OF12_OXM:
617     case OFPUTIL_P_OF13_OXM:
618     case OFPUTIL_P_OF14_OXM:
619     case OFPUTIL_P_OF15_OXM:
620         return oxm_put_match(b, match,
621                              ofputil_protocol_to_ofp_version(protocol));
622     }
623
624     OVS_NOT_REACHED();
625 }
626
627 /* Given a 'dl_type' value in the format used in struct flow, returns the
628  * corresponding 'dl_type' value for use in an ofp10_match or ofp11_match
629  * structure. */
630 ovs_be16
631 ofputil_dl_type_to_openflow(ovs_be16 flow_dl_type)
632 {
633     return (flow_dl_type == htons(FLOW_DL_TYPE_NONE)
634             ? htons(OFP_DL_TYPE_NOT_ETH_TYPE)
635             : flow_dl_type);
636 }
637
638 /* Given a 'dl_type' value in the format used in an ofp10_match or ofp11_match
639  * structure, returns the corresponding 'dl_type' value for use in struct
640  * flow. */
641 ovs_be16
642 ofputil_dl_type_from_openflow(ovs_be16 ofp_dl_type)
643 {
644     return (ofp_dl_type == htons(OFP_DL_TYPE_NOT_ETH_TYPE)
645             ? htons(FLOW_DL_TYPE_NONE)
646             : ofp_dl_type);
647 }
648 \f
649 /* Protocols. */
650
651 struct proto_abbrev {
652     enum ofputil_protocol protocol;
653     const char *name;
654 };
655
656 /* Most users really don't care about some of the differences between
657  * protocols.  These abbreviations help with that. */
658 static const struct proto_abbrev proto_abbrevs[] = {
659     { OFPUTIL_P_ANY,          "any" },
660     { OFPUTIL_P_OF10_STD_ANY, "OpenFlow10" },
661     { OFPUTIL_P_OF10_NXM_ANY, "NXM" },
662     { OFPUTIL_P_ANY_OXM,      "OXM" },
663 };
664 #define N_PROTO_ABBREVS ARRAY_SIZE(proto_abbrevs)
665
666 enum ofputil_protocol ofputil_flow_dump_protocols[] = {
667     OFPUTIL_P_OF15_OXM,
668     OFPUTIL_P_OF14_OXM,
669     OFPUTIL_P_OF13_OXM,
670     OFPUTIL_P_OF12_OXM,
671     OFPUTIL_P_OF11_STD,
672     OFPUTIL_P_OF10_NXM,
673     OFPUTIL_P_OF10_STD,
674 };
675 size_t ofputil_n_flow_dump_protocols = ARRAY_SIZE(ofputil_flow_dump_protocols);
676
677 /* Returns the set of ofputil_protocols that are supported with the given
678  * OpenFlow 'version'.  'version' should normally be an 8-bit OpenFlow version
679  * identifier (e.g. 0x01 for OpenFlow 1.0, 0x02 for OpenFlow 1.1).  Returns 0
680  * if 'version' is not supported or outside the valid range.  */
681 enum ofputil_protocol
682 ofputil_protocols_from_ofp_version(enum ofp_version version)
683 {
684     switch (version) {
685     case OFP10_VERSION:
686         return OFPUTIL_P_OF10_STD_ANY | OFPUTIL_P_OF10_NXM_ANY;
687     case OFP11_VERSION:
688         return OFPUTIL_P_OF11_STD;
689     case OFP12_VERSION:
690         return OFPUTIL_P_OF12_OXM;
691     case OFP13_VERSION:
692         return OFPUTIL_P_OF13_OXM;
693     case OFP14_VERSION:
694         return OFPUTIL_P_OF14_OXM;
695     case OFP15_VERSION:
696         return OFPUTIL_P_OF15_OXM;
697     default:
698         return 0;
699     }
700 }
701
702 /* Returns the ofputil_protocol that is initially in effect on an OpenFlow
703  * connection that has negotiated the given 'version'.  'version' should
704  * normally be an 8-bit OpenFlow version identifier (e.g. 0x01 for OpenFlow
705  * 1.0, 0x02 for OpenFlow 1.1).  Returns 0 if 'version' is not supported or
706  * outside the valid range.  */
707 enum ofputil_protocol
708 ofputil_protocol_from_ofp_version(enum ofp_version version)
709 {
710     return rightmost_1bit(ofputil_protocols_from_ofp_version(version));
711 }
712
713 /* Returns the OpenFlow protocol version number (e.g. OFP10_VERSION,
714  * etc.) that corresponds to 'protocol'. */
715 enum ofp_version
716 ofputil_protocol_to_ofp_version(enum ofputil_protocol protocol)
717 {
718     switch (protocol) {
719     case OFPUTIL_P_OF10_STD:
720     case OFPUTIL_P_OF10_STD_TID:
721     case OFPUTIL_P_OF10_NXM:
722     case OFPUTIL_P_OF10_NXM_TID:
723         return OFP10_VERSION;
724     case OFPUTIL_P_OF11_STD:
725         return OFP11_VERSION;
726     case OFPUTIL_P_OF12_OXM:
727         return OFP12_VERSION;
728     case OFPUTIL_P_OF13_OXM:
729         return OFP13_VERSION;
730     case OFPUTIL_P_OF14_OXM:
731         return OFP14_VERSION;
732     case OFPUTIL_P_OF15_OXM:
733         return OFP15_VERSION;
734     }
735
736     OVS_NOT_REACHED();
737 }
738
739 /* Returns a bitmap of OpenFlow versions that are supported by at
740  * least one of the 'protocols'. */
741 uint32_t
742 ofputil_protocols_to_version_bitmap(enum ofputil_protocol protocols)
743 {
744     uint32_t bitmap = 0;
745
746     for (; protocols; protocols = zero_rightmost_1bit(protocols)) {
747         enum ofputil_protocol protocol = rightmost_1bit(protocols);
748
749         bitmap |= 1u << ofputil_protocol_to_ofp_version(protocol);
750     }
751
752     return bitmap;
753 }
754
755 /* Returns the set of protocols that are supported on top of the
756  * OpenFlow versions included in 'bitmap'. */
757 enum ofputil_protocol
758 ofputil_protocols_from_version_bitmap(uint32_t bitmap)
759 {
760     enum ofputil_protocol protocols = 0;
761
762     for (; bitmap; bitmap = zero_rightmost_1bit(bitmap)) {
763         enum ofp_version version = rightmost_1bit_idx(bitmap);
764
765         protocols |= ofputil_protocols_from_ofp_version(version);
766     }
767
768     return protocols;
769 }
770
771 /* Returns true if 'protocol' is a single OFPUTIL_P_* value, false
772  * otherwise. */
773 bool
774 ofputil_protocol_is_valid(enum ofputil_protocol protocol)
775 {
776     return protocol & OFPUTIL_P_ANY && is_pow2(protocol);
777 }
778
779 /* Returns the equivalent of 'protocol' with the Nicira flow_mod_table_id
780  * extension turned on or off if 'enable' is true or false, respectively.
781  *
782  * This extension is only useful for protocols whose "standard" version does
783  * not allow specific tables to be modified.  In particular, this is true of
784  * OpenFlow 1.0.  In later versions of OpenFlow, a flow_mod request always
785  * specifies a table ID and so there is no need for such an extension.  When
786  * 'protocol' is such a protocol that doesn't need a flow_mod_table_id
787  * extension, this function just returns its 'protocol' argument unchanged
788  * regardless of the value of 'enable'.  */
789 enum ofputil_protocol
790 ofputil_protocol_set_tid(enum ofputil_protocol protocol, bool enable)
791 {
792     switch (protocol) {
793     case OFPUTIL_P_OF10_STD:
794     case OFPUTIL_P_OF10_STD_TID:
795         return enable ? OFPUTIL_P_OF10_STD_TID : OFPUTIL_P_OF10_STD;
796
797     case OFPUTIL_P_OF10_NXM:
798     case OFPUTIL_P_OF10_NXM_TID:
799         return enable ? OFPUTIL_P_OF10_NXM_TID : OFPUTIL_P_OF10_NXM;
800
801     case OFPUTIL_P_OF11_STD:
802         return OFPUTIL_P_OF11_STD;
803
804     case OFPUTIL_P_OF12_OXM:
805         return OFPUTIL_P_OF12_OXM;
806
807     case OFPUTIL_P_OF13_OXM:
808         return OFPUTIL_P_OF13_OXM;
809
810     case OFPUTIL_P_OF14_OXM:
811         return OFPUTIL_P_OF14_OXM;
812
813     case OFPUTIL_P_OF15_OXM:
814         return OFPUTIL_P_OF15_OXM;
815
816     default:
817         OVS_NOT_REACHED();
818     }
819 }
820
821 /* Returns the "base" version of 'protocol'.  That is, if 'protocol' includes
822  * some extension to a standard protocol version, the return value is the
823  * standard version of that protocol without any extension.  If 'protocol' is a
824  * standard protocol version, returns 'protocol' unchanged. */
825 enum ofputil_protocol
826 ofputil_protocol_to_base(enum ofputil_protocol protocol)
827 {
828     return ofputil_protocol_set_tid(protocol, false);
829 }
830
831 /* Returns 'new_base' with any extensions taken from 'cur'. */
832 enum ofputil_protocol
833 ofputil_protocol_set_base(enum ofputil_protocol cur,
834                           enum ofputil_protocol new_base)
835 {
836     bool tid = (cur & OFPUTIL_P_TID) != 0;
837
838     switch (new_base) {
839     case OFPUTIL_P_OF10_STD:
840     case OFPUTIL_P_OF10_STD_TID:
841         return ofputil_protocol_set_tid(OFPUTIL_P_OF10_STD, tid);
842
843     case OFPUTIL_P_OF10_NXM:
844     case OFPUTIL_P_OF10_NXM_TID:
845         return ofputil_protocol_set_tid(OFPUTIL_P_OF10_NXM, tid);
846
847     case OFPUTIL_P_OF11_STD:
848         return ofputil_protocol_set_tid(OFPUTIL_P_OF11_STD, tid);
849
850     case OFPUTIL_P_OF12_OXM:
851         return ofputil_protocol_set_tid(OFPUTIL_P_OF12_OXM, tid);
852
853     case OFPUTIL_P_OF13_OXM:
854         return ofputil_protocol_set_tid(OFPUTIL_P_OF13_OXM, tid);
855
856     case OFPUTIL_P_OF14_OXM:
857         return ofputil_protocol_set_tid(OFPUTIL_P_OF14_OXM, tid);
858
859     case OFPUTIL_P_OF15_OXM:
860         return ofputil_protocol_set_tid(OFPUTIL_P_OF15_OXM, tid);
861
862     default:
863         OVS_NOT_REACHED();
864     }
865 }
866
867 /* Returns a string form of 'protocol', if a simple form exists (that is, if
868  * 'protocol' is either a single protocol or it is a combination of protocols
869  * that have a single abbreviation).  Otherwise, returns NULL. */
870 const char *
871 ofputil_protocol_to_string(enum ofputil_protocol protocol)
872 {
873     const struct proto_abbrev *p;
874
875     /* Use a "switch" statement for single-bit names so that we get a compiler
876      * warning if we forget any. */
877     switch (protocol) {
878     case OFPUTIL_P_OF10_NXM:
879         return "NXM-table_id";
880
881     case OFPUTIL_P_OF10_NXM_TID:
882         return "NXM+table_id";
883
884     case OFPUTIL_P_OF10_STD:
885         return "OpenFlow10-table_id";
886
887     case OFPUTIL_P_OF10_STD_TID:
888         return "OpenFlow10+table_id";
889
890     case OFPUTIL_P_OF11_STD:
891         return "OpenFlow11";
892
893     case OFPUTIL_P_OF12_OXM:
894         return "OXM-OpenFlow12";
895
896     case OFPUTIL_P_OF13_OXM:
897         return "OXM-OpenFlow13";
898
899     case OFPUTIL_P_OF14_OXM:
900         return "OXM-OpenFlow14";
901
902     case OFPUTIL_P_OF15_OXM:
903         return "OXM-OpenFlow15";
904     }
905
906     /* Check abbreviations. */
907     for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
908         if (protocol == p->protocol) {
909             return p->name;
910         }
911     }
912
913     return NULL;
914 }
915
916 /* Returns a string that represents 'protocols'.  The return value might be a
917  * comma-separated list if 'protocols' doesn't have a simple name.  The return
918  * value is "none" if 'protocols' is 0.
919  *
920  * The caller must free the returned string (with free()). */
921 char *
922 ofputil_protocols_to_string(enum ofputil_protocol protocols)
923 {
924     struct ds s;
925
926     ovs_assert(!(protocols & ~OFPUTIL_P_ANY));
927     if (protocols == 0) {
928         return xstrdup("none");
929     }
930
931     ds_init(&s);
932     while (protocols) {
933         const struct proto_abbrev *p;
934         int i;
935
936         if (s.length) {
937             ds_put_char(&s, ',');
938         }
939
940         for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
941             if ((protocols & p->protocol) == p->protocol) {
942                 ds_put_cstr(&s, p->name);
943                 protocols &= ~p->protocol;
944                 goto match;
945             }
946         }
947
948         for (i = 0; i < CHAR_BIT * sizeof(enum ofputil_protocol); i++) {
949             enum ofputil_protocol bit = 1u << i;
950
951             if (protocols & bit) {
952                 ds_put_cstr(&s, ofputil_protocol_to_string(bit));
953                 protocols &= ~bit;
954                 goto match;
955             }
956         }
957         OVS_NOT_REACHED();
958
959     match: ;
960     }
961     return ds_steal_cstr(&s);
962 }
963
964 static enum ofputil_protocol
965 ofputil_protocol_from_string__(const char *s, size_t n)
966 {
967     const struct proto_abbrev *p;
968     int i;
969
970     for (i = 0; i < CHAR_BIT * sizeof(enum ofputil_protocol); i++) {
971         enum ofputil_protocol bit = 1u << i;
972         const char *name = ofputil_protocol_to_string(bit);
973
974         if (name && n == strlen(name) && !strncasecmp(s, name, n)) {
975             return bit;
976         }
977     }
978
979     for (p = proto_abbrevs; p < &proto_abbrevs[N_PROTO_ABBREVS]; p++) {
980         if (n == strlen(p->name) && !strncasecmp(s, p->name, n)) {
981             return p->protocol;
982         }
983     }
984
985     return 0;
986 }
987
988 /* Returns the nonempty set of protocols represented by 's', which can be a
989  * single protocol name or abbreviation or a comma-separated list of them.
990  *
991  * Aborts the program with an error message if 's' is invalid. */
992 enum ofputil_protocol
993 ofputil_protocols_from_string(const char *s)
994 {
995     const char *orig_s = s;
996     enum ofputil_protocol protocols;
997
998     protocols = 0;
999     while (*s) {
1000         enum ofputil_protocol p;
1001         size_t n;
1002
1003         n = strcspn(s, ",");
1004         if (n == 0) {
1005             s++;
1006             continue;
1007         }
1008
1009         p = ofputil_protocol_from_string__(s, n);
1010         if (!p) {
1011             ovs_fatal(0, "%.*s: unknown flow protocol", (int) n, s);
1012         }
1013         protocols |= p;
1014
1015         s += n;
1016     }
1017
1018     if (!protocols) {
1019         ovs_fatal(0, "%s: no flow protocol specified", orig_s);
1020     }
1021     return protocols;
1022 }
1023
1024 enum ofp_version
1025 ofputil_version_from_string(const char *s)
1026 {
1027     if (!strcasecmp(s, "OpenFlow10")) {
1028         return OFP10_VERSION;
1029     }
1030     if (!strcasecmp(s, "OpenFlow11")) {
1031         return OFP11_VERSION;
1032     }
1033     if (!strcasecmp(s, "OpenFlow12")) {
1034         return OFP12_VERSION;
1035     }
1036     if (!strcasecmp(s, "OpenFlow13")) {
1037         return OFP13_VERSION;
1038     }
1039     if (!strcasecmp(s, "OpenFlow14")) {
1040         return OFP14_VERSION;
1041     }
1042     if (!strcasecmp(s, "OpenFlow15")) {
1043         return OFP15_VERSION;
1044     }
1045     return 0;
1046 }
1047
1048 static bool
1049 is_delimiter(unsigned char c)
1050 {
1051     return isspace(c) || c == ',';
1052 }
1053
1054 uint32_t
1055 ofputil_versions_from_string(const char *s)
1056 {
1057     size_t i = 0;
1058     uint32_t bitmap = 0;
1059
1060     while (s[i]) {
1061         size_t j;
1062         int version;
1063         char *key;
1064
1065         if (is_delimiter(s[i])) {
1066             i++;
1067             continue;
1068         }
1069         j = 0;
1070         while (s[i + j] && !is_delimiter(s[i + j])) {
1071             j++;
1072         }
1073         key = xmemdup0(s + i, j);
1074         version = ofputil_version_from_string(key);
1075         if (!version) {
1076             VLOG_FATAL("Unknown OpenFlow version: \"%s\"", key);
1077         }
1078         free(key);
1079         bitmap |= 1u << version;
1080         i += j;
1081     }
1082
1083     return bitmap;
1084 }
1085
1086 uint32_t
1087 ofputil_versions_from_strings(char ** const s, size_t count)
1088 {
1089     uint32_t bitmap = 0;
1090
1091     while (count--) {
1092         int version = ofputil_version_from_string(s[count]);
1093         if (!version) {
1094             VLOG_WARN("Unknown OpenFlow version: \"%s\"", s[count]);
1095         } else {
1096             bitmap |= 1u << version;
1097         }
1098     }
1099
1100     return bitmap;
1101 }
1102
1103 const char *
1104 ofputil_version_to_string(enum ofp_version ofp_version)
1105 {
1106     switch (ofp_version) {
1107     case OFP10_VERSION:
1108         return "OpenFlow10";
1109     case OFP11_VERSION:
1110         return "OpenFlow11";
1111     case OFP12_VERSION:
1112         return "OpenFlow12";
1113     case OFP13_VERSION:
1114         return "OpenFlow13";
1115     case OFP14_VERSION:
1116         return "OpenFlow14";
1117     case OFP15_VERSION:
1118         return "OpenFlow15";
1119     default:
1120         OVS_NOT_REACHED();
1121     }
1122 }
1123
1124 bool
1125 ofputil_packet_in_format_is_valid(enum nx_packet_in_format packet_in_format)
1126 {
1127     switch (packet_in_format) {
1128     case NXPIF_STANDARD:
1129     case NXPIF_NXT_PACKET_IN:
1130     case NXPIF_NXT_PACKET_IN2:
1131         return true;
1132     }
1133
1134     return false;
1135 }
1136
1137 const char *
1138 ofputil_packet_in_format_to_string(enum nx_packet_in_format packet_in_format)
1139 {
1140     switch (packet_in_format) {
1141     case NXPIF_STANDARD:
1142         return "standard";
1143     case NXPIF_NXT_PACKET_IN:
1144         return "nxt_packet_in";
1145     case NXPIF_NXT_PACKET_IN2:
1146         return "nxt_packet_in2";
1147     default:
1148         OVS_NOT_REACHED();
1149     }
1150 }
1151
1152 int
1153 ofputil_packet_in_format_from_string(const char *s)
1154 {
1155     return (!strcmp(s, "standard") || !strcmp(s, "openflow10")
1156             ? NXPIF_STANDARD
1157             : !strcmp(s, "nxt_packet_in") || !strcmp(s, "nxm")
1158             ? NXPIF_NXT_PACKET_IN
1159             : !strcmp(s, "nxt_packet_in2")
1160             ? NXPIF_NXT_PACKET_IN2
1161             : -1);
1162 }
1163
1164 void
1165 ofputil_format_version(struct ds *msg, enum ofp_version version)
1166 {
1167     ds_put_format(msg, "0x%02x", version);
1168 }
1169
1170 void
1171 ofputil_format_version_name(struct ds *msg, enum ofp_version version)
1172 {
1173     ds_put_cstr(msg, ofputil_version_to_string(version));
1174 }
1175
1176 static void
1177 ofputil_format_version_bitmap__(struct ds *msg, uint32_t bitmap,
1178                                 void (*format_version)(struct ds *msg,
1179                                                        enum ofp_version))
1180 {
1181     while (bitmap) {
1182         format_version(msg, raw_ctz(bitmap));
1183         bitmap = zero_rightmost_1bit(bitmap);
1184         if (bitmap) {
1185             ds_put_cstr(msg, ", ");
1186         }
1187     }
1188 }
1189
1190 void
1191 ofputil_format_version_bitmap(struct ds *msg, uint32_t bitmap)
1192 {
1193     ofputil_format_version_bitmap__(msg, bitmap, ofputil_format_version);
1194 }
1195
1196 void
1197 ofputil_format_version_bitmap_names(struct ds *msg, uint32_t bitmap)
1198 {
1199     ofputil_format_version_bitmap__(msg, bitmap, ofputil_format_version_name);
1200 }
1201
1202 static bool
1203 ofputil_decode_hello_bitmap(const struct ofp_hello_elem_header *oheh,
1204                             uint32_t *allowed_versionsp)
1205 {
1206     uint16_t bitmap_len = ntohs(oheh->length) - sizeof *oheh;
1207     const ovs_be32 *bitmap = ALIGNED_CAST(const ovs_be32 *, oheh + 1);
1208     uint32_t allowed_versions;
1209
1210     if (!bitmap_len || bitmap_len % sizeof *bitmap) {
1211         return false;
1212     }
1213
1214     /* Only use the first 32-bit element of the bitmap as that is all the
1215      * current implementation supports.  Subsequent elements are ignored which
1216      * should have no effect on session negotiation until Open vSwitch supports
1217      * wire-protocol versions greater than 31.
1218      */
1219     allowed_versions = ntohl(bitmap[0]);
1220
1221     if (allowed_versions & 1) {
1222         /* There's no OpenFlow version 0. */
1223         VLOG_WARN_RL(&bad_ofmsg_rl, "peer claims to support invalid OpenFlow "
1224                      "version 0x00");
1225         allowed_versions &= ~1u;
1226     }
1227
1228     if (!allowed_versions) {
1229         VLOG_WARN_RL(&bad_ofmsg_rl, "peer does not support any OpenFlow "
1230                      "version (between 0x01 and 0x1f)");
1231         return false;
1232     }
1233
1234     *allowed_versionsp = allowed_versions;
1235     return true;
1236 }
1237
1238 static uint32_t
1239 version_bitmap_from_version(uint8_t ofp_version)
1240 {
1241     return ((ofp_version < 32 ? 1u << ofp_version : 0) - 1) << 1;
1242 }
1243
1244 /* Decodes OpenFlow OFPT_HELLO message 'oh', storing into '*allowed_versions'
1245  * the set of OpenFlow versions for which 'oh' announces support.
1246  *
1247  * Because of how OpenFlow defines OFPT_HELLO messages, this function is always
1248  * successful, and thus '*allowed_versions' is always initialized.  However, it
1249  * returns false if 'oh' contains some data that could not be fully understood,
1250  * true if 'oh' was completely parsed. */
1251 bool
1252 ofputil_decode_hello(const struct ofp_header *oh, uint32_t *allowed_versions)
1253 {
1254     struct ofpbuf msg = ofpbuf_const_initializer(oh, ntohs(oh->length));
1255     ofpbuf_pull(&msg, sizeof *oh);
1256
1257     *allowed_versions = version_bitmap_from_version(oh->version);
1258
1259     bool ok = true;
1260     while (msg.size) {
1261         const struct ofp_hello_elem_header *oheh;
1262         unsigned int len;
1263
1264         if (msg.size < sizeof *oheh) {
1265             return false;
1266         }
1267
1268         oheh = msg.data;
1269         len = ntohs(oheh->length);
1270         if (len < sizeof *oheh || !ofpbuf_try_pull(&msg, ROUND_UP(len, 8))) {
1271             return false;
1272         }
1273
1274         if (oheh->type != htons(OFPHET_VERSIONBITMAP)
1275             || !ofputil_decode_hello_bitmap(oheh, allowed_versions)) {
1276             ok = false;
1277         }
1278     }
1279
1280     return ok;
1281 }
1282
1283 /* Returns true if 'allowed_versions' needs to be accompanied by a version
1284  * bitmap to be correctly expressed in an OFPT_HELLO message. */
1285 static bool
1286 should_send_version_bitmap(uint32_t allowed_versions)
1287 {
1288     return !is_pow2((allowed_versions >> 1) + 1);
1289 }
1290
1291 /* Create an OFPT_HELLO message that expresses support for the OpenFlow
1292  * versions in the 'allowed_versions' bitmaps and returns the message. */
1293 struct ofpbuf *
1294 ofputil_encode_hello(uint32_t allowed_versions)
1295 {
1296     enum ofp_version ofp_version;
1297     struct ofpbuf *msg;
1298
1299     ofp_version = leftmost_1bit_idx(allowed_versions);
1300     msg = ofpraw_alloc(OFPRAW_OFPT_HELLO, ofp_version, 0);
1301
1302     if (should_send_version_bitmap(allowed_versions)) {
1303         struct ofp_hello_elem_header *oheh;
1304         uint16_t map_len;
1305
1306         map_len = sizeof allowed_versions;
1307         oheh = ofpbuf_put_zeros(msg, ROUND_UP(map_len + sizeof *oheh, 8));
1308         oheh->type = htons(OFPHET_VERSIONBITMAP);
1309         oheh->length = htons(map_len + sizeof *oheh);
1310         *ALIGNED_CAST(ovs_be32 *, oheh + 1) = htonl(allowed_versions);
1311
1312         ofpmsg_update_length(msg);
1313     }
1314
1315     return msg;
1316 }
1317
1318 /* Returns an OpenFlow message that, sent on an OpenFlow connection whose
1319  * protocol is 'current', at least partly transitions the protocol to 'want'.
1320  * Stores in '*next' the protocol that will be in effect on the OpenFlow
1321  * connection if the switch processes the returned message correctly.  (If
1322  * '*next != want' then the caller will have to iterate.)
1323  *
1324  * If 'current == want', or if it is not possible to transition from 'current'
1325  * to 'want' (because, for example, 'current' and 'want' use different OpenFlow
1326  * protocol versions), returns NULL and stores 'current' in '*next'. */
1327 struct ofpbuf *
1328 ofputil_encode_set_protocol(enum ofputil_protocol current,
1329                             enum ofputil_protocol want,
1330                             enum ofputil_protocol *next)
1331 {
1332     enum ofp_version cur_version, want_version;
1333     enum ofputil_protocol cur_base, want_base;
1334     bool cur_tid, want_tid;
1335
1336     cur_version = ofputil_protocol_to_ofp_version(current);
1337     want_version = ofputil_protocol_to_ofp_version(want);
1338     if (cur_version != want_version) {
1339         *next = current;
1340         return NULL;
1341     }
1342
1343     cur_base = ofputil_protocol_to_base(current);
1344     want_base = ofputil_protocol_to_base(want);
1345     if (cur_base != want_base) {
1346         *next = ofputil_protocol_set_base(current, want_base);
1347
1348         switch (want_base) {
1349         case OFPUTIL_P_OF10_NXM:
1350             return ofputil_encode_nx_set_flow_format(NXFF_NXM);
1351
1352         case OFPUTIL_P_OF10_STD:
1353             return ofputil_encode_nx_set_flow_format(NXFF_OPENFLOW10);
1354
1355         case OFPUTIL_P_OF11_STD:
1356         case OFPUTIL_P_OF12_OXM:
1357         case OFPUTIL_P_OF13_OXM:
1358         case OFPUTIL_P_OF14_OXM:
1359         case OFPUTIL_P_OF15_OXM:
1360             /* There is only one variant of each OpenFlow 1.1+ protocol, and we
1361              * verified above that we're not trying to change versions. */
1362             OVS_NOT_REACHED();
1363
1364         case OFPUTIL_P_OF10_STD_TID:
1365         case OFPUTIL_P_OF10_NXM_TID:
1366             OVS_NOT_REACHED();
1367         }
1368     }
1369
1370     cur_tid = (current & OFPUTIL_P_TID) != 0;
1371     want_tid = (want & OFPUTIL_P_TID) != 0;
1372     if (cur_tid != want_tid) {
1373         *next = ofputil_protocol_set_tid(current, want_tid);
1374         return ofputil_make_flow_mod_table_id(want_tid);
1375     }
1376
1377     ovs_assert(current == want);
1378
1379     *next = current;
1380     return NULL;
1381 }
1382
1383 /* Returns an NXT_SET_FLOW_FORMAT message that can be used to set the flow
1384  * format to 'nxff'.  */
1385 struct ofpbuf *
1386 ofputil_encode_nx_set_flow_format(enum nx_flow_format nxff)
1387 {
1388     struct nx_set_flow_format *sff;
1389     struct ofpbuf *msg;
1390
1391     ovs_assert(ofputil_nx_flow_format_is_valid(nxff));
1392
1393     msg = ofpraw_alloc(OFPRAW_NXT_SET_FLOW_FORMAT, OFP10_VERSION, 0);
1394     sff = ofpbuf_put_zeros(msg, sizeof *sff);
1395     sff->format = htonl(nxff);
1396
1397     return msg;
1398 }
1399
1400 /* Returns the base protocol if 'flow_format' is a valid NXFF_* value, false
1401  * otherwise. */
1402 enum ofputil_protocol
1403 ofputil_nx_flow_format_to_protocol(enum nx_flow_format flow_format)
1404 {
1405     switch (flow_format) {
1406     case NXFF_OPENFLOW10:
1407         return OFPUTIL_P_OF10_STD;
1408
1409     case NXFF_NXM:
1410         return OFPUTIL_P_OF10_NXM;
1411
1412     default:
1413         return 0;
1414     }
1415 }
1416
1417 /* Returns true if 'flow_format' is a valid NXFF_* value, false otherwise. */
1418 bool
1419 ofputil_nx_flow_format_is_valid(enum nx_flow_format flow_format)
1420 {
1421     return ofputil_nx_flow_format_to_protocol(flow_format) != 0;
1422 }
1423
1424 /* Returns a string version of 'flow_format', which must be a valid NXFF_*
1425  * value. */
1426 const char *
1427 ofputil_nx_flow_format_to_string(enum nx_flow_format flow_format)
1428 {
1429     switch (flow_format) {
1430     case NXFF_OPENFLOW10:
1431         return "openflow10";
1432     case NXFF_NXM:
1433         return "nxm";
1434     default:
1435         OVS_NOT_REACHED();
1436     }
1437 }
1438
1439 struct ofpbuf *
1440 ofputil_make_set_packet_in_format(enum ofp_version ofp_version,
1441                                   enum nx_packet_in_format packet_in_format)
1442 {
1443     struct nx_set_packet_in_format *spif;
1444     struct ofpbuf *msg;
1445
1446     msg = ofpraw_alloc(OFPRAW_NXT_SET_PACKET_IN_FORMAT, ofp_version, 0);
1447     spif = ofpbuf_put_zeros(msg, sizeof *spif);
1448     spif->format = htonl(packet_in_format);
1449
1450     return msg;
1451 }
1452
1453 /* Returns an OpenFlow message that can be used to turn the flow_mod_table_id
1454  * extension on or off (according to 'flow_mod_table_id'). */
1455 struct ofpbuf *
1456 ofputil_make_flow_mod_table_id(bool flow_mod_table_id)
1457 {
1458     struct nx_flow_mod_table_id *nfmti;
1459     struct ofpbuf *msg;
1460
1461     msg = ofpraw_alloc(OFPRAW_NXT_FLOW_MOD_TABLE_ID, OFP10_VERSION, 0);
1462     nfmti = ofpbuf_put_zeros(msg, sizeof *nfmti);
1463     nfmti->set = flow_mod_table_id;
1464     return msg;
1465 }
1466
1467 struct ofputil_flow_mod_flag {
1468     uint16_t raw_flag;
1469     enum ofp_version min_version, max_version;
1470     enum ofputil_flow_mod_flags flag;
1471 };
1472
1473 static const struct ofputil_flow_mod_flag ofputil_flow_mod_flags[] = {
1474     { OFPFF_SEND_FLOW_REM,   OFP10_VERSION, 0, OFPUTIL_FF_SEND_FLOW_REM },
1475     { OFPFF_CHECK_OVERLAP,   OFP10_VERSION, 0, OFPUTIL_FF_CHECK_OVERLAP },
1476     { OFPFF10_EMERG,         OFP10_VERSION, OFP10_VERSION,
1477       OFPUTIL_FF_EMERG },
1478     { OFPFF12_RESET_COUNTS,  OFP12_VERSION, 0, OFPUTIL_FF_RESET_COUNTS },
1479     { OFPFF13_NO_PKT_COUNTS, OFP13_VERSION, 0, OFPUTIL_FF_NO_PKT_COUNTS },
1480     { OFPFF13_NO_BYT_COUNTS, OFP13_VERSION, 0, OFPUTIL_FF_NO_BYT_COUNTS },
1481     { 0, 0, 0, 0 },
1482 };
1483
1484 static enum ofperr
1485 ofputil_decode_flow_mod_flags(ovs_be16 raw_flags_,
1486                               enum ofp_flow_mod_command command,
1487                               enum ofp_version version,
1488                               enum ofputil_flow_mod_flags *flagsp)
1489 {
1490     uint16_t raw_flags = ntohs(raw_flags_);
1491     const struct ofputil_flow_mod_flag *f;
1492
1493     *flagsp = 0;
1494     for (f = ofputil_flow_mod_flags; f->raw_flag; f++) {
1495         if (raw_flags & f->raw_flag
1496             && version >= f->min_version
1497             && (!f->max_version || version <= f->max_version)) {
1498             raw_flags &= ~f->raw_flag;
1499             *flagsp |= f->flag;
1500         }
1501     }
1502
1503     /* In OF1.0 and OF1.1, "add" always resets counters, and other commands
1504      * never do.
1505      *
1506      * In OF1.2 and later, OFPFF12_RESET_COUNTS controls whether each command
1507      * resets counters. */
1508     if ((version == OFP10_VERSION || version == OFP11_VERSION)
1509         && command == OFPFC_ADD) {
1510         *flagsp |= OFPUTIL_FF_RESET_COUNTS;
1511     }
1512
1513     return raw_flags ? OFPERR_OFPFMFC_BAD_FLAGS : 0;
1514 }
1515
1516 static ovs_be16
1517 ofputil_encode_flow_mod_flags(enum ofputil_flow_mod_flags flags,
1518                               enum ofp_version version)
1519 {
1520     const struct ofputil_flow_mod_flag *f;
1521     uint16_t raw_flags;
1522
1523     raw_flags = 0;
1524     for (f = ofputil_flow_mod_flags; f->raw_flag; f++) {
1525         if (f->flag & flags
1526             && version >= f->min_version
1527             && (!f->max_version || version <= f->max_version)) {
1528             raw_flags |= f->raw_flag;
1529         }
1530     }
1531
1532     return htons(raw_flags);
1533 }
1534
1535 /* Converts an OFPT_FLOW_MOD or NXT_FLOW_MOD message 'oh' into an abstract
1536  * flow_mod in 'fm'.  Returns 0 if successful, otherwise an OpenFlow error
1537  * code.
1538  *
1539  * Uses 'ofpacts' to store the abstract OFPACT_* version of 'oh''s actions.
1540  * The caller must initialize 'ofpacts' and retains ownership of it.
1541  * 'fm->ofpacts' will point into the 'ofpacts' buffer.
1542  *
1543  * Does not validate the flow_mod actions.  The caller should do that, with
1544  * ofpacts_check(). */
1545 enum ofperr
1546 ofputil_decode_flow_mod(struct ofputil_flow_mod *fm,
1547                         const struct ofp_header *oh,
1548                         enum ofputil_protocol protocol,
1549                         struct ofpbuf *ofpacts,
1550                         ofp_port_t max_port, uint8_t max_table)
1551 {
1552     ovs_be16 raw_flags;
1553     enum ofperr error;
1554
1555     /* Ignored for non-delete actions */
1556     fm->delete_reason = OFPRR_DELETE;
1557
1558     struct ofpbuf b = ofpbuf_const_initializer(oh, ntohs(oh->length));
1559     enum ofpraw raw = ofpraw_pull_assert(&b);
1560     if (raw == OFPRAW_OFPT11_FLOW_MOD) {
1561         /* Standard OpenFlow 1.1+ flow_mod. */
1562         const struct ofp11_flow_mod *ofm;
1563
1564         ofm = ofpbuf_pull(&b, sizeof *ofm);
1565
1566         error = ofputil_pull_ofp11_match(&b, &fm->match, NULL);
1567         if (error) {
1568             return error;
1569         }
1570
1571         /* Translate the message. */
1572         fm->priority = ntohs(ofm->priority);
1573         if (ofm->command == OFPFC_ADD
1574             || (oh->version == OFP11_VERSION
1575                 && (ofm->command == OFPFC_MODIFY ||
1576                     ofm->command == OFPFC_MODIFY_STRICT)
1577                 && ofm->cookie_mask == htonll(0))) {
1578             /* In OpenFlow 1.1 only, a "modify" or "modify-strict" that does
1579              * not match on the cookie is treated as an "add" if there is no
1580              * match. */
1581             fm->cookie = htonll(0);
1582             fm->cookie_mask = htonll(0);
1583             fm->new_cookie = ofm->cookie;
1584         } else {
1585             fm->cookie = ofm->cookie;
1586             fm->cookie_mask = ofm->cookie_mask;
1587             fm->new_cookie = OVS_BE64_MAX;
1588         }
1589         fm->modify_cookie = false;
1590         fm->command = ofm->command;
1591
1592         /* Get table ID.
1593          *
1594          * OF1.1 entirely forbids table_id == OFPTT_ALL.
1595          * OF1.2+ allows table_id == OFPTT_ALL only for deletes. */
1596         fm->table_id = ofm->table_id;
1597         if (fm->table_id == OFPTT_ALL
1598             && (oh->version == OFP11_VERSION
1599                 || (ofm->command != OFPFC_DELETE &&
1600                     ofm->command != OFPFC_DELETE_STRICT))) {
1601             return OFPERR_OFPFMFC_BAD_TABLE_ID;
1602         }
1603
1604         fm->idle_timeout = ntohs(ofm->idle_timeout);
1605         fm->hard_timeout = ntohs(ofm->hard_timeout);
1606         if (oh->version >= OFP14_VERSION && ofm->command == OFPFC_ADD) {
1607             fm->importance = ntohs(ofm->importance);
1608         } else {
1609             fm->importance = 0;
1610         }
1611         fm->buffer_id = ntohl(ofm->buffer_id);
1612         error = ofputil_port_from_ofp11(ofm->out_port, &fm->out_port);
1613         if (error) {
1614             return error;
1615         }
1616
1617         fm->out_group = (ofm->command == OFPFC_DELETE ||
1618                          ofm->command == OFPFC_DELETE_STRICT
1619                          ? ntohl(ofm->out_group)
1620                          : OFPG_ANY);
1621         raw_flags = ofm->flags;
1622     } else {
1623         uint16_t command;
1624
1625         if (raw == OFPRAW_OFPT10_FLOW_MOD) {
1626             /* Standard OpenFlow 1.0 flow_mod. */
1627             const struct ofp10_flow_mod *ofm;
1628
1629             /* Get the ofp10_flow_mod. */
1630             ofm = ofpbuf_pull(&b, sizeof *ofm);
1631
1632             /* Translate the rule. */
1633             ofputil_match_from_ofp10_match(&ofm->match, &fm->match);
1634             ofputil_normalize_match(&fm->match);
1635
1636             /* OpenFlow 1.0 says that exact-match rules have to have the
1637              * highest possible priority. */
1638             fm->priority = (ofm->match.wildcards & htonl(OFPFW10_ALL)
1639                             ? ntohs(ofm->priority)
1640                             : UINT16_MAX);
1641
1642             /* Translate the message. */
1643             command = ntohs(ofm->command);
1644             fm->cookie = htonll(0);
1645             fm->cookie_mask = htonll(0);
1646             fm->new_cookie = ofm->cookie;
1647             fm->idle_timeout = ntohs(ofm->idle_timeout);
1648             fm->hard_timeout = ntohs(ofm->hard_timeout);
1649             fm->importance = 0;
1650             fm->buffer_id = ntohl(ofm->buffer_id);
1651             fm->out_port = u16_to_ofp(ntohs(ofm->out_port));
1652             fm->out_group = OFPG_ANY;
1653             raw_flags = ofm->flags;
1654         } else if (raw == OFPRAW_NXT_FLOW_MOD) {
1655             /* Nicira extended flow_mod. */
1656             const struct nx_flow_mod *nfm;
1657
1658             /* Dissect the message. */
1659             nfm = ofpbuf_pull(&b, sizeof *nfm);
1660             error = nx_pull_match(&b, ntohs(nfm->match_len),
1661                                   &fm->match, &fm->cookie, &fm->cookie_mask);
1662             if (error) {
1663                 return error;
1664             }
1665
1666             /* Translate the message. */
1667             command = ntohs(nfm->command);
1668             if ((command & 0xff) == OFPFC_ADD && fm->cookie_mask) {
1669                 /* Flow additions may only set a new cookie, not match an
1670                  * existing cookie. */
1671                 return OFPERR_NXBRC_NXM_INVALID;
1672             }
1673             fm->priority = ntohs(nfm->priority);
1674             fm->new_cookie = nfm->cookie;
1675             fm->idle_timeout = ntohs(nfm->idle_timeout);
1676             fm->hard_timeout = ntohs(nfm->hard_timeout);
1677             fm->importance = 0;
1678             fm->buffer_id = ntohl(nfm->buffer_id);
1679             fm->out_port = u16_to_ofp(ntohs(nfm->out_port));
1680             fm->out_group = OFPG_ANY;
1681             raw_flags = nfm->flags;
1682         } else {
1683             OVS_NOT_REACHED();
1684         }
1685
1686         fm->modify_cookie = fm->new_cookie != OVS_BE64_MAX;
1687         if (protocol & OFPUTIL_P_TID) {
1688             fm->command = command & 0xff;
1689             fm->table_id = command >> 8;
1690         } else {
1691             if (command > 0xff) {
1692                 VLOG_WARN_RL(&bad_ofmsg_rl, "flow_mod has explicit table_id "
1693                              "but flow_mod_table_id extension is not enabled");
1694             }
1695             fm->command = command;
1696             fm->table_id = 0xff;
1697         }
1698     }
1699
1700     if (fm->command > OFPFC_DELETE_STRICT) {
1701         return OFPERR_OFPFMFC_BAD_COMMAND;
1702     }
1703
1704     error = ofpacts_pull_openflow_instructions(&b, b.size,
1705                                                oh->version, ofpacts);
1706     if (error) {
1707         return error;
1708     }
1709     fm->ofpacts = ofpacts->data;
1710     fm->ofpacts_len = ofpacts->size;
1711
1712     error = ofputil_decode_flow_mod_flags(raw_flags, fm->command,
1713                                           oh->version, &fm->flags);
1714     if (error) {
1715         return error;
1716     }
1717
1718     if (fm->flags & OFPUTIL_FF_EMERG) {
1719         /* We do not support the OpenFlow 1.0 emergency flow cache, which
1720          * is not required in OpenFlow 1.0.1 and removed from OpenFlow 1.1.
1721          *
1722          * OpenFlow 1.0 specifies the error code to use when idle_timeout
1723          * or hard_timeout is nonzero.  Otherwise, there is no good error
1724          * code, so just state that the flow table is full. */
1725         return (fm->hard_timeout || fm->idle_timeout
1726                 ? OFPERR_OFPFMFC_BAD_EMERG_TIMEOUT
1727                 : OFPERR_OFPFMFC_TABLE_FULL);
1728     }
1729
1730     return ofpacts_check_consistency(fm->ofpacts, fm->ofpacts_len,
1731                                      &fm->match.flow, max_port,
1732                                      fm->table_id, max_table, protocol);
1733 }
1734
1735 static enum ofperr
1736 ofputil_pull_bands(struct ofpbuf *msg, size_t len, uint16_t *n_bands,
1737                    struct ofpbuf *bands)
1738 {
1739     const struct ofp13_meter_band_header *ombh;
1740     struct ofputil_meter_band *mb;
1741     uint16_t n = 0;
1742
1743     ombh = ofpbuf_try_pull(msg, len);
1744     if (!ombh) {
1745         return OFPERR_OFPBRC_BAD_LEN;
1746     }
1747
1748     while (len >= sizeof (struct ofp13_meter_band_drop)) {
1749         size_t ombh_len = ntohs(ombh->len);
1750         /* All supported band types have the same length. */
1751         if (ombh_len != sizeof (struct ofp13_meter_band_drop)) {
1752             return OFPERR_OFPBRC_BAD_LEN;
1753         }
1754         mb = ofpbuf_put_uninit(bands, sizeof *mb);
1755         mb->type = ntohs(ombh->type);
1756         if (mb->type != OFPMBT13_DROP && mb->type != OFPMBT13_DSCP_REMARK) {
1757             return OFPERR_OFPMMFC_BAD_BAND;
1758         }
1759         mb->rate = ntohl(ombh->rate);
1760         mb->burst_size = ntohl(ombh->burst_size);
1761         mb->prec_level = (mb->type == OFPMBT13_DSCP_REMARK) ?
1762             ((struct ofp13_meter_band_dscp_remark *)ombh)->prec_level : 0;
1763         n++;
1764         len -= ombh_len;
1765         ombh = ALIGNED_CAST(struct ofp13_meter_band_header *,
1766                             (char *) ombh + ombh_len);
1767     }
1768     if (len) {
1769         return OFPERR_OFPBRC_BAD_LEN;
1770     }
1771     *n_bands = n;
1772     return 0;
1773 }
1774
1775 enum ofperr
1776 ofputil_decode_meter_mod(const struct ofp_header *oh,
1777                          struct ofputil_meter_mod *mm,
1778                          struct ofpbuf *bands)
1779 {
1780     struct ofpbuf b = ofpbuf_const_initializer(oh, ntohs(oh->length));
1781     ofpraw_pull_assert(&b);
1782     const struct ofp13_meter_mod *omm = ofpbuf_pull(&b, sizeof *omm);
1783
1784     /* Translate the message. */
1785     mm->command = ntohs(omm->command);
1786     if (mm->command != OFPMC13_ADD &&
1787         mm->command != OFPMC13_MODIFY &&
1788         mm->command != OFPMC13_DELETE) {
1789         return OFPERR_OFPMMFC_BAD_COMMAND;
1790     }
1791     mm->meter.meter_id = ntohl(omm->meter_id);
1792
1793     if (mm->command == OFPMC13_DELETE) {
1794         mm->meter.flags = 0;
1795         mm->meter.n_bands = 0;
1796         mm->meter.bands = NULL;
1797     } else {
1798         enum ofperr error;
1799
1800         mm->meter.flags = ntohs(omm->flags);
1801         if (mm->meter.flags & OFPMF13_KBPS &&
1802             mm->meter.flags & OFPMF13_PKTPS) {
1803             return OFPERR_OFPMMFC_BAD_FLAGS;
1804         }
1805         mm->meter.bands = bands->data;
1806
1807         error = ofputil_pull_bands(&b, b.size, &mm->meter.n_bands, bands);
1808         if (error) {
1809             return error;
1810         }
1811     }
1812     return 0;
1813 }
1814
1815 void
1816 ofputil_decode_meter_request(const struct ofp_header *oh, uint32_t *meter_id)
1817 {
1818     const struct ofp13_meter_multipart_request *omr = ofpmsg_body(oh);
1819     *meter_id = ntohl(omr->meter_id);
1820 }
1821
1822 struct ofpbuf *
1823 ofputil_encode_meter_request(enum ofp_version ofp_version,
1824                              enum ofputil_meter_request_type type,
1825                              uint32_t meter_id)
1826 {
1827     struct ofpbuf *msg;
1828
1829     enum ofpraw raw;
1830
1831     switch (type) {
1832     case OFPUTIL_METER_CONFIG:
1833         raw = OFPRAW_OFPST13_METER_CONFIG_REQUEST;
1834         break;
1835     case OFPUTIL_METER_STATS:
1836         raw = OFPRAW_OFPST13_METER_REQUEST;
1837         break;
1838     default:
1839     case OFPUTIL_METER_FEATURES:
1840         raw = OFPRAW_OFPST13_METER_FEATURES_REQUEST;
1841         break;
1842     }
1843
1844     msg = ofpraw_alloc(raw, ofp_version, 0);
1845
1846     if (type != OFPUTIL_METER_FEATURES) {
1847         struct ofp13_meter_multipart_request *omr;
1848         omr = ofpbuf_put_zeros(msg, sizeof *omr);
1849         omr->meter_id = htonl(meter_id);
1850     }
1851     return msg;
1852 }
1853
1854 static void
1855 ofputil_put_bands(uint16_t n_bands, const struct ofputil_meter_band *mb,
1856                   struct ofpbuf *msg)
1857 {
1858     uint16_t n = 0;
1859
1860     for (n = 0; n < n_bands; ++n) {
1861         /* Currently all band types have same size. */
1862         struct ofp13_meter_band_dscp_remark *ombh;
1863         size_t ombh_len = sizeof *ombh;
1864
1865         ombh = ofpbuf_put_zeros(msg, ombh_len);
1866
1867         ombh->type = htons(mb->type);
1868         ombh->len = htons(ombh_len);
1869         ombh->rate = htonl(mb->rate);
1870         ombh->burst_size = htonl(mb->burst_size);
1871         ombh->prec_level = mb->prec_level;
1872
1873         mb++;
1874     }
1875 }
1876
1877 /* Encode a meter stat for 'mc' and append it to 'replies'. */
1878 void
1879 ofputil_append_meter_config(struct ovs_list *replies,
1880                             const struct ofputil_meter_config *mc)
1881 {
1882     struct ofpbuf *msg = ofpbuf_from_list(list_back(replies));
1883     size_t start_ofs = msg->size;
1884     struct ofp13_meter_config *reply;
1885
1886     ofpbuf_put_uninit(msg, sizeof *reply);
1887     ofputil_put_bands(mc->n_bands, mc->bands, msg);
1888
1889     reply = ofpbuf_at_assert(msg, start_ofs, sizeof *reply);
1890     reply->flags = htons(mc->flags);
1891     reply->meter_id = htonl(mc->meter_id);
1892     reply->length = htons(msg->size - start_ofs);
1893
1894     ofpmp_postappend(replies, start_ofs);
1895 }
1896
1897 /* Encode a meter stat for 'ms' and append it to 'replies'. */
1898 void
1899 ofputil_append_meter_stats(struct ovs_list *replies,
1900                            const struct ofputil_meter_stats *ms)
1901 {
1902     struct ofp13_meter_stats *reply;
1903     uint16_t n = 0;
1904     uint16_t len;
1905
1906     len = sizeof *reply + ms->n_bands * sizeof(struct ofp13_meter_band_stats);
1907     reply = ofpmp_append(replies, len);
1908
1909     reply->meter_id = htonl(ms->meter_id);
1910     reply->len = htons(len);
1911     memset(reply->pad, 0, sizeof reply->pad);
1912     reply->flow_count = htonl(ms->flow_count);
1913     reply->packet_in_count = htonll(ms->packet_in_count);
1914     reply->byte_in_count = htonll(ms->byte_in_count);
1915     reply->duration_sec = htonl(ms->duration_sec);
1916     reply->duration_nsec = htonl(ms->duration_nsec);
1917
1918     for (n = 0; n < ms->n_bands; ++n) {
1919         const struct ofputil_meter_band_stats *src = &ms->bands[n];
1920         struct ofp13_meter_band_stats *dst = &reply->band_stats[n];
1921
1922         dst->packet_band_count = htonll(src->packet_count);
1923         dst->byte_band_count = htonll(src->byte_count);
1924     }
1925 }
1926
1927 /* Converts an OFPMP_METER_CONFIG reply in 'msg' into an abstract
1928  * ofputil_meter_config in 'mc', with mc->bands pointing to bands decoded into
1929  * 'bands'.  The caller must have initialized 'bands' and retains ownership of
1930  * it across the call.
1931  *
1932  * Multiple OFPST13_METER_CONFIG replies can be packed into a single OpenFlow
1933  * message.  Calling this function multiple times for a single 'msg' iterates
1934  * through the replies.  'bands' is cleared for each reply.
1935  *
1936  * Returns 0 if successful, EOF if no replies were left in this 'msg',
1937  * otherwise a positive errno value. */
1938 int
1939 ofputil_decode_meter_config(struct ofpbuf *msg,
1940                             struct ofputil_meter_config *mc,
1941                             struct ofpbuf *bands)
1942 {
1943     const struct ofp13_meter_config *omc;
1944     enum ofperr err;
1945
1946     /* Pull OpenFlow headers for the first call. */
1947     if (!msg->header) {
1948         ofpraw_pull_assert(msg);
1949     }
1950
1951     if (!msg->size) {
1952         return EOF;
1953     }
1954
1955     omc = ofpbuf_try_pull(msg, sizeof *omc);
1956     if (!omc) {
1957         VLOG_WARN_RL(&bad_ofmsg_rl,
1958                      "OFPMP_METER_CONFIG reply has %"PRIu32" leftover bytes at end",
1959                      msg->size);
1960         return OFPERR_OFPBRC_BAD_LEN;
1961     }
1962
1963     ofpbuf_clear(bands);
1964     err = ofputil_pull_bands(msg, ntohs(omc->length) - sizeof *omc,
1965                              &mc->n_bands, bands);
1966     if (err) {
1967         return err;
1968     }
1969     mc->meter_id = ntohl(omc->meter_id);
1970     mc->flags = ntohs(omc->flags);
1971     mc->bands = bands->data;
1972
1973     return 0;
1974 }
1975
1976 static enum ofperr
1977 ofputil_pull_band_stats(struct ofpbuf *msg, size_t len, uint16_t *n_bands,
1978                         struct ofpbuf *bands)
1979 {
1980     const struct ofp13_meter_band_stats *ombs;
1981     struct ofputil_meter_band_stats *mbs;
1982     uint16_t n, i;
1983
1984     ombs = ofpbuf_try_pull(msg, len);
1985     if (!ombs) {
1986         return OFPERR_OFPBRC_BAD_LEN;
1987     }
1988
1989     n = len / sizeof *ombs;
1990     if (len != n * sizeof *ombs) {
1991         return OFPERR_OFPBRC_BAD_LEN;
1992     }
1993
1994     mbs = ofpbuf_put_uninit(bands, len);
1995
1996     for (i = 0; i < n; ++i) {
1997         mbs[i].packet_count = ntohll(ombs[i].packet_band_count);
1998         mbs[i].byte_count = ntohll(ombs[i].byte_band_count);
1999     }
2000     *n_bands = n;
2001     return 0;
2002 }
2003
2004 /* Converts an OFPMP_METER reply in 'msg' into an abstract
2005  * ofputil_meter_stats in 'ms', with ms->bands pointing to band stats
2006  * decoded into 'bands'.
2007  *
2008  * Multiple OFPMP_METER replies can be packed into a single OpenFlow
2009  * message.  Calling this function multiple times for a single 'msg' iterates
2010  * through the replies.  'bands' is cleared for each reply.
2011  *
2012  * Returns 0 if successful, EOF if no replies were left in this 'msg',
2013  * otherwise a positive errno value. */
2014 int
2015 ofputil_decode_meter_stats(struct ofpbuf *msg,
2016                            struct ofputil_meter_stats *ms,
2017                            struct ofpbuf *bands)
2018 {
2019     const struct ofp13_meter_stats *oms;
2020     enum ofperr err;
2021
2022     /* Pull OpenFlow headers for the first call. */
2023     if (!msg->header) {
2024         ofpraw_pull_assert(msg);
2025     }
2026
2027     if (!msg->size) {
2028         return EOF;
2029     }
2030
2031     oms = ofpbuf_try_pull(msg, sizeof *oms);
2032     if (!oms) {
2033         VLOG_WARN_RL(&bad_ofmsg_rl,
2034                      "OFPMP_METER reply has %"PRIu32" leftover bytes at end",
2035                      msg->size);
2036         return OFPERR_OFPBRC_BAD_LEN;
2037     }
2038
2039     ofpbuf_clear(bands);
2040     err = ofputil_pull_band_stats(msg, ntohs(oms->len) - sizeof *oms,
2041                                   &ms->n_bands, bands);
2042     if (err) {
2043         return err;
2044     }
2045     ms->meter_id = ntohl(oms->meter_id);
2046     ms->flow_count = ntohl(oms->flow_count);
2047     ms->packet_in_count = ntohll(oms->packet_in_count);
2048     ms->byte_in_count = ntohll(oms->byte_in_count);
2049     ms->duration_sec = ntohl(oms->duration_sec);
2050     ms->duration_nsec = ntohl(oms->duration_nsec);
2051     ms->bands = bands->data;
2052
2053     return 0;
2054 }
2055
2056 void
2057 ofputil_decode_meter_features(const struct ofp_header *oh,
2058                               struct ofputil_meter_features *mf)
2059 {
2060     const struct ofp13_meter_features *omf = ofpmsg_body(oh);
2061
2062     mf->max_meters = ntohl(omf->max_meter);
2063     mf->band_types = ntohl(omf->band_types);
2064     mf->capabilities = ntohl(omf->capabilities);
2065     mf->max_bands = omf->max_bands;
2066     mf->max_color = omf->max_color;
2067 }
2068
2069 struct ofpbuf *
2070 ofputil_encode_meter_features_reply(const struct ofputil_meter_features *mf,
2071                                     const struct ofp_header *request)
2072 {
2073     struct ofpbuf *reply;
2074     struct ofp13_meter_features *omf;
2075
2076     reply = ofpraw_alloc_stats_reply(request, 0);
2077     omf = ofpbuf_put_zeros(reply, sizeof *omf);
2078
2079     omf->max_meter = htonl(mf->max_meters);
2080     omf->band_types = htonl(mf->band_types);
2081     omf->capabilities = htonl(mf->capabilities);
2082     omf->max_bands = mf->max_bands;
2083     omf->max_color = mf->max_color;
2084
2085     return reply;
2086 }
2087
2088 struct ofpbuf *
2089 ofputil_encode_meter_mod(enum ofp_version ofp_version,
2090                          const struct ofputil_meter_mod *mm)
2091 {
2092     struct ofpbuf *msg;
2093
2094     struct ofp13_meter_mod *omm;
2095
2096     msg = ofpraw_alloc(OFPRAW_OFPT13_METER_MOD, ofp_version,
2097                        NXM_TYPICAL_LEN + mm->meter.n_bands * 16);
2098     omm = ofpbuf_put_zeros(msg, sizeof *omm);
2099     omm->command = htons(mm->command);
2100     if (mm->command != OFPMC13_DELETE) {
2101         omm->flags = htons(mm->meter.flags);
2102     }
2103     omm->meter_id = htonl(mm->meter.meter_id);
2104
2105     ofputil_put_bands(mm->meter.n_bands, mm->meter.bands, msg);
2106
2107     ofpmsg_update_length(msg);
2108     return msg;
2109 }
2110
2111 static ovs_be16
2112 ofputil_tid_command(const struct ofputil_flow_mod *fm,
2113                     enum ofputil_protocol protocol)
2114 {
2115     return htons(protocol & OFPUTIL_P_TID
2116                  ? (fm->command & 0xff) | (fm->table_id << 8)
2117                  : fm->command);
2118 }
2119
2120 /* Converts 'fm' into an OFPT_FLOW_MOD or NXT_FLOW_MOD message according to
2121  * 'protocol' and returns the message. */
2122 struct ofpbuf *
2123 ofputil_encode_flow_mod(const struct ofputil_flow_mod *fm,
2124                         enum ofputil_protocol protocol)
2125 {
2126     enum ofp_version version = ofputil_protocol_to_ofp_version(protocol);
2127     ovs_be16 raw_flags = ofputil_encode_flow_mod_flags(fm->flags, version);
2128     struct ofpbuf *msg;
2129
2130     switch (protocol) {
2131     case OFPUTIL_P_OF11_STD:
2132     case OFPUTIL_P_OF12_OXM:
2133     case OFPUTIL_P_OF13_OXM:
2134     case OFPUTIL_P_OF14_OXM:
2135     case OFPUTIL_P_OF15_OXM: {
2136         struct ofp11_flow_mod *ofm;
2137         int tailroom;
2138
2139         tailroom = ofputil_match_typical_len(protocol) + fm->ofpacts_len;
2140         msg = ofpraw_alloc(OFPRAW_OFPT11_FLOW_MOD, version, tailroom);
2141         ofm = ofpbuf_put_zeros(msg, sizeof *ofm);
2142         if ((protocol == OFPUTIL_P_OF11_STD
2143              && (fm->command == OFPFC_MODIFY ||
2144                  fm->command == OFPFC_MODIFY_STRICT)
2145              && fm->cookie_mask == htonll(0))
2146             || fm->command == OFPFC_ADD) {
2147             ofm->cookie = fm->new_cookie;
2148         } else {
2149             ofm->cookie = fm->cookie & fm->cookie_mask;
2150         }
2151         ofm->cookie_mask = fm->cookie_mask;
2152         if (fm->table_id != OFPTT_ALL
2153             || (protocol != OFPUTIL_P_OF11_STD
2154                 && (fm->command == OFPFC_DELETE ||
2155                     fm->command == OFPFC_DELETE_STRICT))) {
2156             ofm->table_id = fm->table_id;
2157         } else {
2158             ofm->table_id = 0;
2159         }
2160         ofm->command = fm->command;
2161         ofm->idle_timeout = htons(fm->idle_timeout);
2162         ofm->hard_timeout = htons(fm->hard_timeout);
2163         ofm->priority = htons(fm->priority);
2164         ofm->buffer_id = htonl(fm->buffer_id);
2165         ofm->out_port = ofputil_port_to_ofp11(fm->out_port);
2166         ofm->out_group = htonl(fm->out_group);
2167         ofm->flags = raw_flags;
2168         if (version >= OFP14_VERSION && fm->command == OFPFC_ADD) {
2169             ofm->importance = htons(fm->importance);
2170         } else {
2171             ofm->importance = 0;
2172         }
2173         ofputil_put_ofp11_match(msg, &fm->match, protocol);
2174         ofpacts_put_openflow_instructions(fm->ofpacts, fm->ofpacts_len, msg,
2175                                           version);
2176         break;
2177     }
2178
2179     case OFPUTIL_P_OF10_STD:
2180     case OFPUTIL_P_OF10_STD_TID: {
2181         struct ofp10_flow_mod *ofm;
2182
2183         msg = ofpraw_alloc(OFPRAW_OFPT10_FLOW_MOD, OFP10_VERSION,
2184                            fm->ofpacts_len);
2185         ofm = ofpbuf_put_zeros(msg, sizeof *ofm);
2186         ofputil_match_to_ofp10_match(&fm->match, &ofm->match);
2187         ofm->cookie = fm->new_cookie;
2188         ofm->command = ofputil_tid_command(fm, protocol);
2189         ofm->idle_timeout = htons(fm->idle_timeout);
2190         ofm->hard_timeout = htons(fm->hard_timeout);
2191         ofm->priority = htons(fm->priority);
2192         ofm->buffer_id = htonl(fm->buffer_id);
2193         ofm->out_port = htons(ofp_to_u16(fm->out_port));
2194         ofm->flags = raw_flags;
2195         ofpacts_put_openflow_actions(fm->ofpacts, fm->ofpacts_len, msg,
2196                                      version);
2197         break;
2198     }
2199
2200     case OFPUTIL_P_OF10_NXM:
2201     case OFPUTIL_P_OF10_NXM_TID: {
2202         struct nx_flow_mod *nfm;
2203         int match_len;
2204
2205         msg = ofpraw_alloc(OFPRAW_NXT_FLOW_MOD, OFP10_VERSION,
2206                            NXM_TYPICAL_LEN + fm->ofpacts_len);
2207         nfm = ofpbuf_put_zeros(msg, sizeof *nfm);
2208         nfm->command = ofputil_tid_command(fm, protocol);
2209         nfm->cookie = fm->new_cookie;
2210         match_len = nx_put_match(msg, &fm->match, fm->cookie, fm->cookie_mask);
2211         nfm = msg->msg;
2212         nfm->idle_timeout = htons(fm->idle_timeout);
2213         nfm->hard_timeout = htons(fm->hard_timeout);
2214         nfm->priority = htons(fm->priority);
2215         nfm->buffer_id = htonl(fm->buffer_id);
2216         nfm->out_port = htons(ofp_to_u16(fm->out_port));
2217         nfm->flags = raw_flags;
2218         nfm->match_len = htons(match_len);
2219         ofpacts_put_openflow_actions(fm->ofpacts, fm->ofpacts_len, msg,
2220                                      version);
2221         break;
2222     }
2223
2224     default:
2225         OVS_NOT_REACHED();
2226     }
2227
2228     ofpmsg_update_length(msg);
2229     return msg;
2230 }
2231
2232 static enum ofperr
2233 ofputil_decode_ofpst10_flow_request(struct ofputil_flow_stats_request *fsr,
2234                                     const struct ofp10_flow_stats_request *ofsr,
2235                                     bool aggregate)
2236 {
2237     fsr->aggregate = aggregate;
2238     ofputil_match_from_ofp10_match(&ofsr->match, &fsr->match);
2239     fsr->out_port = u16_to_ofp(ntohs(ofsr->out_port));
2240     fsr->out_group = OFPG_ANY;
2241     fsr->table_id = ofsr->table_id;
2242     fsr->cookie = fsr->cookie_mask = htonll(0);
2243
2244     return 0;
2245 }
2246
2247 static enum ofperr
2248 ofputil_decode_ofpst11_flow_request(struct ofputil_flow_stats_request *fsr,
2249                                     struct ofpbuf *b, bool aggregate)
2250 {
2251     const struct ofp11_flow_stats_request *ofsr;
2252     enum ofperr error;
2253
2254     ofsr = ofpbuf_pull(b, sizeof *ofsr);
2255     fsr->aggregate = aggregate;
2256     fsr->table_id = ofsr->table_id;
2257     error = ofputil_port_from_ofp11(ofsr->out_port, &fsr->out_port);
2258     if (error) {
2259         return error;
2260     }
2261     fsr->out_group = ntohl(ofsr->out_group);
2262     fsr->cookie = ofsr->cookie;
2263     fsr->cookie_mask = ofsr->cookie_mask;
2264     error = ofputil_pull_ofp11_match(b, &fsr->match, NULL);
2265     if (error) {
2266         return error;
2267     }
2268
2269     return 0;
2270 }
2271
2272 static enum ofperr
2273 ofputil_decode_nxst_flow_request(struct ofputil_flow_stats_request *fsr,
2274                                  struct ofpbuf *b, bool aggregate)
2275 {
2276     const struct nx_flow_stats_request *nfsr;
2277     enum ofperr error;
2278
2279     nfsr = ofpbuf_pull(b, sizeof *nfsr);
2280     error = nx_pull_match(b, ntohs(nfsr->match_len), &fsr->match,
2281                           &fsr->cookie, &fsr->cookie_mask);
2282     if (error) {
2283         return error;
2284     }
2285     if (b->size) {
2286         return OFPERR_OFPBRC_BAD_LEN;
2287     }
2288
2289     fsr->aggregate = aggregate;
2290     fsr->out_port = u16_to_ofp(ntohs(nfsr->out_port));
2291     fsr->out_group = OFPG_ANY;
2292     fsr->table_id = nfsr->table_id;
2293
2294     return 0;
2295 }
2296
2297 /* Constructs and returns an OFPT_QUEUE_GET_CONFIG request for the specified
2298  * 'port' and 'queue', suitable for OpenFlow version 'version'.
2299  *
2300  * 'queue' is honored only for OpenFlow 1.4 and later; older versions always
2301  * request all queues. */
2302 struct ofpbuf *
2303 ofputil_encode_queue_get_config_request(enum ofp_version version,
2304                                         ofp_port_t port,
2305                                         uint32_t queue)
2306 {
2307     struct ofpbuf *request;
2308
2309     if (version == OFP10_VERSION) {
2310         struct ofp10_queue_get_config_request *qgcr10;
2311
2312         request = ofpraw_alloc(OFPRAW_OFPT10_QUEUE_GET_CONFIG_REQUEST,
2313                                version, 0);
2314         qgcr10 = ofpbuf_put_zeros(request, sizeof *qgcr10);
2315         qgcr10->port = htons(ofp_to_u16(port));
2316     } else if (version < OFP14_VERSION) {
2317         struct ofp11_queue_get_config_request *qgcr11;
2318
2319         request = ofpraw_alloc(OFPRAW_OFPT11_QUEUE_GET_CONFIG_REQUEST,
2320                                version, 0);
2321         qgcr11 = ofpbuf_put_zeros(request, sizeof *qgcr11);
2322         qgcr11->port = ofputil_port_to_ofp11(port);
2323     } else {
2324         struct ofp14_queue_desc_request *qdr14;
2325
2326         request = ofpraw_alloc(OFPRAW_OFPST14_QUEUE_DESC_REQUEST,
2327                                version, 0);
2328         qdr14 = ofpbuf_put_zeros(request, sizeof *qdr14);
2329         qdr14->port = ofputil_port_to_ofp11(port);
2330         qdr14->queue = htonl(queue);
2331     }
2332
2333     return request;
2334 }
2335
2336 /* Parses OFPT_QUEUE_GET_CONFIG request 'oh', storing the port specified by the
2337  * request into '*port'.  Returns 0 if successful, otherwise an OpenFlow error
2338  * code. */
2339 enum ofperr
2340 ofputil_decode_queue_get_config_request(const struct ofp_header *oh,
2341                                         ofp_port_t *port, uint32_t *queue)
2342 {
2343     const struct ofp10_queue_get_config_request *qgcr10;
2344     const struct ofp11_queue_get_config_request *qgcr11;
2345     const struct ofp14_queue_desc_request *qdr14;
2346     struct ofpbuf b = ofpbuf_const_initializer(oh, ntohs(oh->length));
2347     enum ofpraw raw = ofpraw_pull_assert(&b);
2348
2349     switch ((int) raw) {
2350     case OFPRAW_OFPT10_QUEUE_GET_CONFIG_REQUEST:
2351         qgcr10 = b.data;
2352         *port = u16_to_ofp(ntohs(qgcr10->port));
2353         *queue = OFPQ_ALL;
2354         break;
2355
2356     case OFPRAW_OFPT11_QUEUE_GET_CONFIG_REQUEST:
2357         qgcr11 = b.data;
2358         *queue = OFPQ_ALL;
2359         enum ofperr error = ofputil_port_from_ofp11(qgcr11->port, port);
2360         if (error || *port == OFPP_ANY) {
2361             return error;
2362         }
2363         break;
2364
2365     case OFPRAW_OFPST14_QUEUE_DESC_REQUEST:
2366         qdr14 = b.data;
2367         *queue = ntohl(qdr14->queue);
2368         return ofputil_port_from_ofp11(qdr14->port, port);
2369
2370     default:
2371         OVS_NOT_REACHED();
2372     }
2373
2374     return (ofp_to_u16(*port) < ofp_to_u16(OFPP_MAX)
2375             ? 0
2376             : OFPERR_OFPQOFC_BAD_PORT);
2377 }
2378
2379 /* Constructs and returns the beginning of a reply to
2380  * OFPT_QUEUE_GET_CONFIG_REQUEST or OFPMP_QUEUE_DESC request 'oh'.  The caller
2381  * may append information about individual queues with
2382  * ofputil_append_queue_get_config_reply(). */
2383 void
2384 ofputil_start_queue_get_config_reply(const struct ofp_header *request,
2385                                      struct ovs_list *replies)
2386 {
2387     struct ofpbuf *reply;
2388     enum ofperr error;
2389     ofp_port_t port;
2390     uint32_t queue;
2391
2392     error = ofputil_decode_queue_get_config_request(request, &port, &queue);
2393     ovs_assert(!error);
2394
2395     enum ofpraw raw = ofpraw_decode_assert(request);
2396     switch ((int) raw) {
2397     case OFPRAW_OFPT10_QUEUE_GET_CONFIG_REQUEST:
2398         reply = ofpraw_alloc_reply(OFPRAW_OFPT10_QUEUE_GET_CONFIG_REPLY,
2399                                    request, 0);
2400         struct ofp10_queue_get_config_reply *qgcr10
2401             = ofpbuf_put_zeros(reply, sizeof *qgcr10);
2402         qgcr10->port = htons(ofp_to_u16(port));
2403         break;
2404
2405     case OFPRAW_OFPT11_QUEUE_GET_CONFIG_REQUEST:
2406         reply = ofpraw_alloc_reply(OFPRAW_OFPT11_QUEUE_GET_CONFIG_REPLY,
2407                                    request, 0);
2408         struct ofp11_queue_get_config_reply *qgcr11
2409             = ofpbuf_put_zeros(reply, sizeof *qgcr11);
2410         qgcr11->port = ofputil_port_to_ofp11(port);
2411         break;
2412
2413     case OFPRAW_OFPST14_QUEUE_DESC_REQUEST:
2414         reply = ofpraw_alloc_stats_reply(request, 0);
2415         break;
2416
2417     default:
2418         OVS_NOT_REACHED();
2419     }
2420
2421     list_init(replies);
2422     list_push_back(replies, &reply->list_node);
2423 }
2424
2425 static void
2426 put_ofp10_queue_rate(struct ofpbuf *reply,
2427                      enum ofp10_queue_properties property, uint16_t rate)
2428 {
2429     if (rate != UINT16_MAX) {
2430         struct ofp10_queue_prop_rate *oqpr;
2431
2432         oqpr = ofpbuf_put_zeros(reply, sizeof *oqpr);
2433         oqpr->prop_header.property = htons(property);
2434         oqpr->prop_header.len = htons(sizeof *oqpr);
2435         oqpr->rate = htons(rate);
2436     }
2437 }
2438
2439 static void
2440 put_ofp14_queue_rate(struct ofpbuf *reply,
2441                      enum ofp14_queue_desc_prop_type type, uint16_t rate)
2442 {
2443     if (rate != UINT16_MAX) {
2444         ofpprop_put_u16(reply, type, rate);
2445     }
2446 }
2447
2448 void
2449 ofputil_append_queue_get_config_reply(const struct ofputil_queue_config *qc,
2450                                       struct ovs_list *replies)
2451 {
2452     enum ofp_version ofp_version = ofpmp_version(replies);
2453     struct ofpbuf *reply = ofpbuf_from_list(list_back(replies));
2454     size_t start_ofs = reply->size;
2455     size_t len_ofs;
2456     ovs_be16 *len;
2457
2458     if (ofp_version < OFP14_VERSION) {
2459         if (ofp_version < OFP12_VERSION) {
2460             struct ofp10_packet_queue *opq10;
2461
2462             opq10 = ofpbuf_put_zeros(reply, sizeof *opq10);
2463             opq10->queue_id = htonl(qc->queue);
2464             len_ofs = (char *) &opq10->len - (char *) reply->data;
2465         } else {
2466             struct ofp12_packet_queue *opq12;
2467
2468             opq12 = ofpbuf_put_zeros(reply, sizeof *opq12);
2469             opq12->port = ofputil_port_to_ofp11(qc->port);
2470             opq12->queue_id = htonl(qc->queue);
2471             len_ofs = (char *) &opq12->len - (char *) reply->data;
2472         }
2473
2474         put_ofp10_queue_rate(reply, OFPQT10_MIN_RATE, qc->min_rate);
2475         put_ofp10_queue_rate(reply, OFPQT11_MAX_RATE, qc->max_rate);
2476     } else {
2477         struct ofp14_queue_desc *oqd = ofpbuf_put_zeros(reply, sizeof *oqd);
2478         oqd->port_no = ofputil_port_to_ofp11(qc->port);
2479         oqd->queue_id = htonl(qc->queue);
2480         len_ofs = (char *) &oqd->len - (char *) reply->data;
2481         put_ofp14_queue_rate(reply, OFPQDPT14_MIN_RATE, qc->min_rate);
2482         put_ofp14_queue_rate(reply, OFPQDPT14_MAX_RATE, qc->max_rate);
2483     }
2484
2485     len = ofpbuf_at(reply, len_ofs, sizeof *len);
2486     *len = htons(reply->size - start_ofs);
2487
2488     if (ofp_version >= OFP14_VERSION) {
2489         ofpmp_postappend(replies, start_ofs);
2490     }
2491 }
2492
2493 static enum ofperr
2494 parse_ofp10_queue_rate(const struct ofp10_queue_prop_header *hdr,
2495                        uint16_t *rate)
2496 {
2497     const struct ofp10_queue_prop_rate *oqpr;
2498
2499     if (hdr->len == htons(sizeof *oqpr)) {
2500         oqpr = (const struct ofp10_queue_prop_rate *) hdr;
2501         *rate = ntohs(oqpr->rate);
2502         return 0;
2503     } else {
2504         return OFPERR_OFPBRC_BAD_LEN;
2505     }
2506 }
2507
2508 static int
2509 ofputil_pull_queue_get_config_reply10(struct ofpbuf *msg,
2510                                       struct ofputil_queue_config *queue)
2511 {
2512     const struct ofp_header *oh = msg->header;
2513     unsigned int opq_len;       /* Length of protocol-specific queue header. */
2514     unsigned int len;           /* Total length of queue + properties. */
2515
2516     /* Obtain the port number from the message header. */
2517     if (oh->version == OFP10_VERSION) {
2518         const struct ofp10_queue_get_config_reply *oqgcr10 = msg->msg;
2519         queue->port = u16_to_ofp(ntohs(oqgcr10->port));
2520     } else {
2521         const struct ofp11_queue_get_config_reply *oqgcr11 = msg->msg;
2522         enum ofperr error = ofputil_port_from_ofp11(oqgcr11->port,
2523                                                     &queue->port);
2524         if (error) {
2525             return error;
2526         }
2527     }
2528
2529     /* Pull off the queue header and get the queue number and length. */
2530     if (oh->version < OFP12_VERSION) {
2531         const struct ofp10_packet_queue *opq10;
2532         opq10 = ofpbuf_try_pull(msg, sizeof *opq10);
2533         if (!opq10) {
2534             return OFPERR_OFPBRC_BAD_LEN;
2535         }
2536         queue->queue = ntohl(opq10->queue_id);
2537         len = ntohs(opq10->len);
2538         opq_len = sizeof *opq10;
2539     } else {
2540         const struct ofp12_packet_queue *opq12;
2541         opq12 = ofpbuf_try_pull(msg, sizeof *opq12);
2542         if (!opq12) {
2543             return OFPERR_OFPBRC_BAD_LEN;
2544         }
2545         queue->queue = ntohl(opq12->queue_id);
2546         len = ntohs(opq12->len);
2547         opq_len = sizeof *opq12;
2548     }
2549
2550     /* Length check. */
2551     if (len < opq_len || len > msg->size + opq_len || len % 8) {
2552         return OFPERR_OFPBRC_BAD_LEN;
2553     }
2554     len -= opq_len;
2555
2556     /* Pull properties.  The format of these properties differs from used in
2557      * OF1.4+ so we can't use the common property functions. */
2558     while (len > 0) {
2559         const struct ofp10_queue_prop_header *hdr;
2560         unsigned int property;
2561         unsigned int prop_len;
2562         enum ofperr error = 0;
2563
2564         hdr = ofpbuf_at_assert(msg, 0, sizeof *hdr);
2565         prop_len = ntohs(hdr->len);
2566         if (prop_len < sizeof *hdr || prop_len > msg->size || prop_len % 8) {
2567             return OFPERR_OFPBRC_BAD_LEN;
2568         }
2569
2570         property = ntohs(hdr->property);
2571         switch (property) {
2572         case OFPQT10_MIN_RATE:
2573             error = parse_ofp10_queue_rate(hdr, &queue->min_rate);
2574             break;
2575
2576         case OFPQT11_MAX_RATE:
2577             error = parse_ofp10_queue_rate(hdr, &queue->max_rate);
2578             break;
2579
2580         default:
2581             VLOG_INFO_RL(&bad_ofmsg_rl, "unknown queue property %u", property);
2582             break;
2583         }
2584         if (error) {
2585             return error;
2586         }
2587
2588         ofpbuf_pull(msg, prop_len);
2589         len -= prop_len;
2590     }
2591     return 0;
2592 }
2593
2594 static int
2595 ofputil_pull_queue_get_config_reply14(struct ofpbuf *msg,
2596                                       struct ofputil_queue_config *queue)
2597 {
2598     struct ofp14_queue_desc *oqd14 = ofpbuf_try_pull(msg, sizeof *oqd14);
2599     if (!oqd14) {
2600         return OFPERR_OFPBRC_BAD_LEN;
2601     }
2602     enum ofperr error = ofputil_port_from_ofp11(oqd14->port_no, &queue->port);
2603     if (error) {
2604         return error;
2605     }
2606     queue->queue = ntohl(oqd14->queue_id);
2607
2608     /* Length check. */
2609     unsigned int len = ntohs(oqd14->len);
2610     if (len < sizeof *oqd14 || len > msg->size + sizeof *oqd14 || len % 8) {
2611         return OFPERR_OFPBRC_BAD_LEN;
2612     }
2613     len -= sizeof *oqd14;
2614
2615     struct ofpbuf properties = ofpbuf_const_initializer(ofpbuf_pull(msg, len),
2616                                                         len);
2617     while (properties.size > 0) {
2618         struct ofpbuf payload;
2619         uint64_t type;
2620
2621         error = ofpprop_pull(&properties, &payload, &type);
2622         if (error) {
2623             return error;
2624         }
2625
2626         switch (type) {
2627         case OFPQDPT14_MIN_RATE:
2628             error = ofpprop_parse_u16(&payload, &queue->min_rate);
2629             break;
2630
2631         case OFPQDPT14_MAX_RATE:
2632             error = ofpprop_parse_u16(&payload, &queue->max_rate);
2633             break;
2634
2635         default:
2636             error = OFPPROP_UNKNOWN(true, "queue desc", type);
2637             break;
2638         }
2639
2640         if (error) {
2641             return error;
2642         }
2643     }
2644
2645     return 0;
2646 }
2647
2648 /* Decodes information about a queue from the OFPT_QUEUE_GET_CONFIG_REPLY in
2649  * 'reply' and stores it in '*queue'.  ofputil_decode_queue_get_config_reply()
2650  * must already have pulled off the main header.
2651  *
2652  * This function returns EOF if the last queue has already been decoded, 0 if a
2653  * queue was successfully decoded into '*queue', or an ofperr if there was a
2654  * problem decoding 'reply'. */
2655 int
2656 ofputil_pull_queue_get_config_reply(struct ofpbuf *msg,
2657                                     struct ofputil_queue_config *queue)
2658 {
2659     enum ofpraw raw;
2660     if (!msg->header) {
2661         /* Pull OpenFlow header. */
2662         raw = ofpraw_pull_assert(msg);
2663
2664         /* Pull protocol-specific ofp_queue_get_config_reply header (OF1.4
2665          * doesn't have one at all). */
2666         if (raw == OFPRAW_OFPT10_QUEUE_GET_CONFIG_REPLY) {
2667             ofpbuf_pull(msg, sizeof(struct ofp10_queue_get_config_reply));
2668         } else if (raw == OFPRAW_OFPT11_QUEUE_GET_CONFIG_REPLY) {
2669             ofpbuf_pull(msg, sizeof(struct ofp11_queue_get_config_reply));
2670         } else {
2671             ovs_assert(raw == OFPRAW_OFPST14_QUEUE_DESC_REPLY);
2672         }
2673     } else {
2674         raw = ofpraw_decode_assert(msg->header);
2675     }
2676
2677     queue->min_rate = UINT16_MAX;
2678     queue->max_rate = UINT16_MAX;
2679
2680     if (!msg->size) {
2681         return EOF;
2682     } else if (raw == OFPRAW_OFPST14_QUEUE_DESC_REPLY) {
2683         return ofputil_pull_queue_get_config_reply14(msg, queue);
2684     } else {
2685         return ofputil_pull_queue_get_config_reply10(msg, queue);
2686     }
2687 }
2688
2689 /* Converts an OFPST_FLOW, OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE
2690  * request 'oh', into an abstract flow_stats_request in 'fsr'.  Returns 0 if
2691  * successful, otherwise an OpenFlow error code. */
2692 enum ofperr
2693 ofputil_decode_flow_stats_request(struct ofputil_flow_stats_request *fsr,
2694                                   const struct ofp_header *oh)
2695 {
2696     struct ofpbuf b = ofpbuf_const_initializer(oh, ntohs(oh->length));
2697     enum ofpraw raw = ofpraw_pull_assert(&b);
2698     switch ((int) raw) {
2699     case OFPRAW_OFPST10_FLOW_REQUEST:
2700         return ofputil_decode_ofpst10_flow_request(fsr, b.data, false);
2701
2702     case OFPRAW_OFPST10_AGGREGATE_REQUEST:
2703         return ofputil_decode_ofpst10_flow_request(fsr, b.data, true);
2704
2705     case OFPRAW_OFPST11_FLOW_REQUEST:
2706         return ofputil_decode_ofpst11_flow_request(fsr, &b, false);
2707
2708     case OFPRAW_OFPST11_AGGREGATE_REQUEST:
2709         return ofputil_decode_ofpst11_flow_request(fsr, &b, true);
2710
2711     case OFPRAW_NXST_FLOW_REQUEST:
2712         return ofputil_decode_nxst_flow_request(fsr, &b, false);
2713
2714     case OFPRAW_NXST_AGGREGATE_REQUEST:
2715         return ofputil_decode_nxst_flow_request(fsr, &b, true);
2716
2717     default:
2718         /* Hey, the caller lied. */
2719         OVS_NOT_REACHED();
2720     }
2721 }
2722
2723 /* Converts abstract flow_stats_request 'fsr' into an OFPST_FLOW,
2724  * OFPST_AGGREGATE, NXST_FLOW, or NXST_AGGREGATE request 'oh' according to
2725  * 'protocol', and returns the message. */
2726 struct ofpbuf *
2727 ofputil_encode_flow_stats_request(const struct ofputil_flow_stats_request *fsr,
2728                                   enum ofputil_protocol protocol)
2729 {
2730     struct ofpbuf *msg;
2731     enum ofpraw raw;
2732
2733     switch (protocol) {
2734     case OFPUTIL_P_OF11_STD:
2735     case OFPUTIL_P_OF12_OXM:
2736     case OFPUTIL_P_OF13_OXM:
2737     case OFPUTIL_P_OF14_OXM:
2738     case OFPUTIL_P_OF15_OXM: {
2739         struct ofp11_flow_stats_request *ofsr;
2740
2741         raw = (fsr->aggregate
2742                ? OFPRAW_OFPST11_AGGREGATE_REQUEST
2743                : OFPRAW_OFPST11_FLOW_REQUEST);
2744         msg = ofpraw_alloc(raw, ofputil_protocol_to_ofp_version(protocol),
2745                            ofputil_match_typical_len(protocol));
2746         ofsr = ofpbuf_put_zeros(msg, sizeof *ofsr);
2747         ofsr->table_id = fsr->table_id;
2748         ofsr->out_port = ofputil_port_to_ofp11(fsr->out_port);
2749         ofsr->out_group = htonl(fsr->out_group);
2750         ofsr->cookie = fsr->cookie;
2751         ofsr->cookie_mask = fsr->cookie_mask;
2752         ofputil_put_ofp11_match(msg, &fsr->match, protocol);
2753         break;
2754     }
2755
2756     case OFPUTIL_P_OF10_STD:
2757     case OFPUTIL_P_OF10_STD_TID: {
2758         struct ofp10_flow_stats_request *ofsr;
2759
2760         raw = (fsr->aggregate
2761                ? OFPRAW_OFPST10_AGGREGATE_REQUEST
2762                : OFPRAW_OFPST10_FLOW_REQUEST);
2763         msg = ofpraw_alloc(raw, OFP10_VERSION, 0);
2764         ofsr = ofpbuf_put_zeros(msg, sizeof *ofsr);
2765         ofputil_match_to_ofp10_match(&fsr->match, &ofsr->match);
2766         ofsr->table_id = fsr->table_id;
2767         ofsr->out_port = htons(ofp_to_u16(fsr->out_port));
2768         break;
2769     }
2770
2771     case OFPUTIL_P_OF10_NXM:
2772     case OFPUTIL_P_OF10_NXM_TID: {
2773         struct nx_flow_stats_request *nfsr;
2774         int match_len;
2775
2776         raw = (fsr->aggregate
2777                ? OFPRAW_NXST_AGGREGATE_REQUEST
2778                : OFPRAW_NXST_FLOW_REQUEST);
2779         msg = ofpraw_alloc(raw, OFP10_VERSION, NXM_TYPICAL_LEN);
2780         ofpbuf_put_zeros(msg, sizeof *nfsr);
2781         match_len = nx_put_match(msg, &fsr->match,
2782                                  fsr->cookie, fsr->cookie_mask);
2783
2784         nfsr = msg->msg;
2785         nfsr->out_port = htons(ofp_to_u16(fsr->out_port));
2786         nfsr->match_len = htons(match_len);
2787         nfsr->table_id = fsr->table_id;
2788         break;
2789     }
2790
2791     default:
2792         OVS_NOT_REACHED();
2793     }
2794
2795     return msg;
2796 }
2797
2798 /* Converts an OFPST_FLOW or NXST_FLOW reply in 'msg' into an abstract
2799  * ofputil_flow_stats in 'fs'.
2800  *
2801  * Multiple OFPST_FLOW or NXST_FLOW replies can be packed into a single
2802  * OpenFlow message.  Calling this function multiple times for a single 'msg'
2803  * iterates through the replies.  The caller must initially leave 'msg''s layer
2804  * pointers null and not modify them between calls.
2805  *
2806  * Most switches don't send the values needed to populate fs->idle_age and
2807  * fs->hard_age, so those members will usually be set to 0.  If the switch from
2808  * which 'msg' originated is known to implement NXT_FLOW_AGE, then pass
2809  * 'flow_age_extension' as true so that the contents of 'msg' determine the
2810  * 'idle_age' and 'hard_age' members in 'fs'.
2811  *
2812  * Uses 'ofpacts' to store the abstract OFPACT_* version of the flow stats
2813  * reply's actions.  The caller must initialize 'ofpacts' and retains ownership
2814  * of it.  'fs->ofpacts' will point into the 'ofpacts' buffer.
2815  *
2816  * Returns 0 if successful, EOF if no replies were left in this 'msg',
2817  * otherwise a positive errno value. */
2818 int
2819 ofputil_decode_flow_stats_reply(struct ofputil_flow_stats *fs,
2820                                 struct ofpbuf *msg,
2821                                 bool flow_age_extension,
2822                                 struct ofpbuf *ofpacts)
2823 {
2824     const struct ofp_header *oh;
2825     size_t instructions_len;
2826     enum ofperr error;
2827     enum ofpraw raw;
2828
2829     error = (msg->header ? ofpraw_decode(&raw, msg->header)
2830              : ofpraw_pull(&raw, msg));
2831     if (error) {
2832         return error;
2833     }
2834     oh = msg->header;
2835
2836     if (!msg->size) {
2837         return EOF;
2838     } else if (raw == OFPRAW_OFPST11_FLOW_REPLY
2839                || raw == OFPRAW_OFPST13_FLOW_REPLY) {
2840         const struct ofp11_flow_stats *ofs;
2841         size_t length;
2842         uint16_t padded_match_len;
2843
2844         ofs = ofpbuf_try_pull(msg, sizeof *ofs);
2845         if (!ofs) {
2846             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply has %"PRIu32" leftover "
2847                          "bytes at end", msg->size);
2848             return EINVAL;
2849         }
2850
2851         length = ntohs(ofs->length);
2852         if (length < sizeof *ofs) {
2853             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply claims invalid "
2854                          "length %"PRIuSIZE, length);
2855             return EINVAL;
2856         }
2857
2858         if (ofputil_pull_ofp11_match(msg, &fs->match, &padded_match_len)) {
2859             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply bad match");
2860             return EINVAL;
2861         }
2862         instructions_len = length - sizeof *ofs - padded_match_len;
2863
2864         fs->priority = ntohs(ofs->priority);
2865         fs->table_id = ofs->table_id;
2866         fs->duration_sec = ntohl(ofs->duration_sec);
2867         fs->duration_nsec = ntohl(ofs->duration_nsec);
2868         fs->idle_timeout = ntohs(ofs->idle_timeout);
2869         fs->hard_timeout = ntohs(ofs->hard_timeout);
2870         if (oh->version >= OFP14_VERSION) {
2871             fs->importance = ntohs(ofs->importance);
2872         } else {
2873             fs->importance = 0;
2874         }
2875         if (raw == OFPRAW_OFPST13_FLOW_REPLY) {
2876             error = ofputil_decode_flow_mod_flags(ofs->flags, -1, oh->version,
2877                                                   &fs->flags);
2878             if (error) {
2879                 return error;
2880             }
2881         } else {
2882             fs->flags = 0;
2883         }
2884         fs->idle_age = -1;
2885         fs->hard_age = -1;
2886         fs->cookie = ofs->cookie;
2887         fs->packet_count = ntohll(ofs->packet_count);
2888         fs->byte_count = ntohll(ofs->byte_count);
2889     } else if (raw == OFPRAW_OFPST10_FLOW_REPLY) {
2890         const struct ofp10_flow_stats *ofs;
2891         size_t length;
2892
2893         ofs = ofpbuf_try_pull(msg, sizeof *ofs);
2894         if (!ofs) {
2895             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply has %"PRIu32" leftover "
2896                          "bytes at end", msg->size);
2897             return EINVAL;
2898         }
2899
2900         length = ntohs(ofs->length);
2901         if (length < sizeof *ofs) {
2902             VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply claims invalid "
2903                          "length %"PRIuSIZE, length);
2904             return EINVAL;
2905         }
2906         instructions_len = length - sizeof *ofs;
2907
2908         fs->cookie = get_32aligned_be64(&ofs->cookie);
2909         ofputil_match_from_ofp10_match(&ofs->match, &fs->match);
2910         fs->priority = ntohs(ofs->priority);
2911         fs->table_id = ofs->table_id;
2912         fs->duration_sec = ntohl(ofs->duration_sec);
2913         fs->duration_nsec = ntohl(ofs->duration_nsec);
2914         fs->idle_timeout = ntohs(ofs->idle_timeout);
2915         fs->hard_timeout = ntohs(ofs->hard_timeout);
2916         fs->importance = 0;
2917         fs->idle_age = -1;
2918         fs->hard_age = -1;
2919         fs->packet_count = ntohll(get_32aligned_be64(&ofs->packet_count));
2920         fs->byte_count = ntohll(get_32aligned_be64(&ofs->byte_count));
2921         fs->flags = 0;
2922     } else if (raw == OFPRAW_NXST_FLOW_REPLY) {
2923         const struct nx_flow_stats *nfs;
2924         size_t match_len, length;
2925
2926         nfs = ofpbuf_try_pull(msg, sizeof *nfs);
2927         if (!nfs) {
2928             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply has %"PRIu32" leftover "
2929                          "bytes at end", msg->size);
2930             return EINVAL;
2931         }
2932
2933         length = ntohs(nfs->length);
2934         match_len = ntohs(nfs->match_len);
2935         if (length < sizeof *nfs + ROUND_UP(match_len, 8)) {
2936             VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW reply with match_len=%"PRIuSIZE" "
2937                          "claims invalid length %"PRIuSIZE, match_len, length);
2938             return EINVAL;
2939         }
2940         if (nx_pull_match(msg, match_len, &fs->match, NULL, NULL)) {
2941             return EINVAL;
2942         }
2943         instructions_len = length - sizeof *nfs - ROUND_UP(match_len, 8);
2944
2945         fs->cookie = nfs->cookie;
2946         fs->table_id = nfs->table_id;
2947         fs->duration_sec = ntohl(nfs->duration_sec);
2948         fs->duration_nsec = ntohl(nfs->duration_nsec);
2949         fs->priority = ntohs(nfs->priority);
2950         fs->idle_timeout = ntohs(nfs->idle_timeout);
2951         fs->hard_timeout = ntohs(nfs->hard_timeout);
2952         fs->importance = 0;
2953         fs->idle_age = -1;
2954         fs->hard_age = -1;
2955         if (flow_age_extension) {
2956             if (nfs->idle_age) {
2957                 fs->idle_age = ntohs(nfs->idle_age) - 1;
2958             }
2959             if (nfs->hard_age) {
2960                 fs->hard_age = ntohs(nfs->hard_age) - 1;
2961             }
2962         }
2963         fs->packet_count = ntohll(nfs->packet_count);
2964         fs->byte_count = ntohll(nfs->byte_count);
2965         fs->flags = 0;
2966     } else {
2967         OVS_NOT_REACHED();
2968     }
2969
2970     if (ofpacts_pull_openflow_instructions(msg, instructions_len, oh->version,
2971                                            ofpacts)) {
2972         VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_FLOW reply bad instructions");
2973         return EINVAL;
2974     }
2975     fs->ofpacts = ofpacts->data;
2976     fs->ofpacts_len = ofpacts->size;
2977
2978     return 0;
2979 }
2980
2981 /* Returns 'count' unchanged except that UINT64_MAX becomes 0.
2982  *
2983  * We use this in situations where OVS internally uses UINT64_MAX to mean
2984  * "value unknown" but OpenFlow 1.0 does not define any unknown value. */
2985 static uint64_t
2986 unknown_to_zero(uint64_t count)
2987 {
2988     return count != UINT64_MAX ? count : 0;
2989 }
2990
2991 /* Appends an OFPST_FLOW or NXST_FLOW reply that contains the data in 'fs' to
2992  * those already present in the list of ofpbufs in 'replies'.  'replies' should
2993  * have been initialized with ofpmp_init(). */
2994 void
2995 ofputil_append_flow_stats_reply(const struct ofputil_flow_stats *fs,
2996                                 struct ovs_list *replies)
2997 {
2998     struct ofpbuf *reply = ofpbuf_from_list(list_back(replies));
2999     size_t start_ofs = reply->size;
3000     enum ofp_version version = ofpmp_version(replies);
3001     enum ofpraw raw = ofpmp_decode_raw(replies);
3002
3003     if (raw == OFPRAW_OFPST11_FLOW_REPLY || raw == OFPRAW_OFPST13_FLOW_REPLY) {
3004         struct ofp11_flow_stats *ofs;
3005
3006         ofpbuf_put_uninit(reply, sizeof *ofs);
3007         oxm_put_match(reply, &fs->match, version);
3008         ofpacts_put_openflow_instructions(fs->ofpacts, fs->ofpacts_len, reply,
3009                                           version);
3010
3011         ofs = ofpbuf_at_assert(reply, start_ofs, sizeof *ofs);
3012         ofs->length = htons(reply->size - start_ofs);
3013         ofs->table_id = fs->table_id;
3014         ofs->pad = 0;
3015         ofs->duration_sec = htonl(fs->duration_sec);
3016         ofs->duration_nsec = htonl(fs->duration_nsec);
3017         ofs->priority = htons(fs->priority);
3018         ofs->idle_timeout = htons(fs->idle_timeout);
3019         ofs->hard_timeout = htons(fs->hard_timeout);
3020         if (version >= OFP14_VERSION) {
3021             ofs->importance = htons(fs->importance);
3022         } else {
3023             ofs->importance = 0;
3024         }
3025         if (raw == OFPRAW_OFPST13_FLOW_REPLY) {
3026             ofs->flags = ofputil_encode_flow_mod_flags(fs->flags, version);
3027         } else {
3028             ofs->flags = 0;
3029         }
3030         memset(ofs->pad2, 0, sizeof ofs->pad2);
3031         ofs->cookie = fs->cookie;
3032         ofs->packet_count = htonll(unknown_to_zero(fs->packet_count));
3033         ofs->byte_count = htonll(unknown_to_zero(fs->byte_count));
3034     } else if (raw == OFPRAW_OFPST10_FLOW_REPLY) {
3035         struct ofp10_flow_stats *ofs;
3036
3037         ofpbuf_put_uninit(reply, sizeof *ofs);
3038         ofpacts_put_openflow_actions(fs->ofpacts, fs->ofpacts_len, reply,
3039                                      version);
3040         ofs = ofpbuf_at_assert(reply, start_ofs, sizeof *ofs);
3041         ofs->length = htons(reply->size - start_ofs);
3042         ofs->table_id = fs->table_id;
3043         ofs->pad = 0;
3044         ofputil_match_to_ofp10_match(&fs->match, &ofs->match);
3045         ofs->duration_sec = htonl(fs->duration_sec);
3046         ofs->duration_nsec = htonl(fs->duration_nsec);
3047         ofs->priority = htons(fs->priority);
3048         ofs->idle_timeout = htons(fs->idle_timeout);
3049         ofs->hard_timeout = htons(fs->hard_timeout);
3050         memset(ofs->pad2, 0, sizeof ofs->pad2);
3051         put_32aligned_be64(&ofs->cookie, fs->cookie);
3052         put_32aligned_be64(&ofs->packet_count,
3053                            htonll(unknown_to_zero(fs->packet_count)));
3054         put_32aligned_be64(&ofs->byte_count,
3055                            htonll(unknown_to_zero(fs->byte_count)));
3056     } else if (raw == OFPRAW_NXST_FLOW_REPLY) {
3057         struct nx_flow_stats *nfs;
3058         int match_len;
3059
3060         ofpbuf_put_uninit(reply, sizeof *nfs);
3061         match_len = nx_put_match(reply, &fs->match, 0, 0);
3062         ofpacts_put_openflow_actions(fs->ofpacts, fs->ofpacts_len, reply,
3063                                      version);
3064         nfs = ofpbuf_at_assert(reply, start_ofs, sizeof *nfs);
3065         nfs->length = htons(reply->size - start_ofs);
3066         nfs->table_id = fs->table_id;
3067         nfs->pad = 0;
3068         nfs->duration_sec = htonl(fs->duration_sec);
3069         nfs->duration_nsec = htonl(fs->duration_nsec);
3070         nfs->priority = htons(fs->priority);
3071         nfs->idle_timeout = htons(fs->idle_timeout);
3072         nfs->hard_timeout = htons(fs->hard_timeout);
3073         nfs->idle_age = htons(fs->idle_age < 0 ? 0
3074                               : fs->idle_age < UINT16_MAX ? fs->idle_age + 1
3075                               : UINT16_MAX);
3076         nfs->hard_age = htons(fs->hard_age < 0 ? 0
3077                               : fs->hard_age < UINT16_MAX ? fs->hard_age + 1
3078                               : UINT16_MAX);
3079         nfs->match_len = htons(match_len);
3080         nfs->cookie = fs->cookie;
3081         nfs->packet_count = htonll(fs->packet_count);
3082         nfs->byte_count = htonll(fs->byte_count);
3083     } else {
3084         OVS_NOT_REACHED();
3085     }
3086
3087     ofpmp_postappend(replies, start_ofs);
3088 }
3089
3090 /* Converts abstract ofputil_aggregate_stats 'stats' into an OFPST_AGGREGATE or
3091  * NXST_AGGREGATE reply matching 'request', and returns the message. */
3092 struct ofpbuf *
3093 ofputil_encode_aggregate_stats_reply(
3094     const struct ofputil_aggregate_stats *stats,
3095     const struct ofp_header *request)
3096 {
3097     struct ofp_aggregate_stats_reply *asr;
3098     uint64_t packet_count;
3099     uint64_t byte_count;
3100     struct ofpbuf *msg;
3101     enum ofpraw raw;
3102
3103     ofpraw_decode(&raw, request);
3104     if (raw == OFPRAW_OFPST10_AGGREGATE_REQUEST) {
3105         packet_count = unknown_to_zero(stats->packet_count);
3106         byte_count = unknown_to_zero(stats->byte_count);
3107     } else {
3108         packet_count = stats->packet_count;
3109         byte_count = stats->byte_count;
3110     }
3111
3112     msg = ofpraw_alloc_stats_reply(request, 0);
3113     asr = ofpbuf_put_zeros(msg, sizeof *asr);
3114     put_32aligned_be64(&asr->packet_count, htonll(packet_count));
3115     put_32aligned_be64(&asr->byte_count, htonll(byte_count));
3116     asr->flow_count = htonl(stats->flow_count);
3117
3118     return msg;
3119 }
3120
3121 enum ofperr
3122 ofputil_decode_aggregate_stats_reply(struct ofputil_aggregate_stats *stats,
3123                                      const struct ofp_header *reply)
3124 {
3125     struct ofpbuf msg = ofpbuf_const_initializer(reply, ntohs(reply->length));
3126     ofpraw_pull_assert(&msg);
3127
3128     struct ofp_aggregate_stats_reply *asr = msg.msg;
3129     stats->packet_count = ntohll(get_32aligned_be64(&asr->packet_count));
3130     stats->byte_count = ntohll(get_32aligned_be64(&asr->byte_count));
3131     stats->flow_count = ntohl(asr->flow_count);
3132
3133     return 0;
3134 }
3135
3136 /* Converts an OFPT_FLOW_REMOVED or NXT_FLOW_REMOVED message 'oh' into an
3137  * abstract ofputil_flow_removed in 'fr'.  Returns 0 if successful, otherwise
3138  * an OpenFlow error code. */
3139 enum ofperr
3140 ofputil_decode_flow_removed(struct ofputil_flow_removed *fr,
3141                             const struct ofp_header *oh)
3142 {
3143     struct ofpbuf b = ofpbuf_const_initializer(oh, ntohs(oh->length));
3144     enum ofpraw raw = ofpraw_pull_assert(&b);
3145     if (raw == OFPRAW_OFPT11_FLOW_REMOVED) {
3146         const struct ofp12_flow_removed *ofr;
3147         enum ofperr error;
3148
3149         ofr = ofpbuf_pull(&b, sizeof *ofr);
3150
3151         error = ofputil_pull_ofp11_match(&b, &fr->match, NULL);
3152         if (error) {
3153             return error;
3154         }
3155
3156         fr->priority = ntohs(ofr->priority);
3157         fr->cookie = ofr->cookie;
3158         fr->reason = ofr->reason;
3159         fr->table_id = ofr->table_id;
3160         fr->duration_sec = ntohl(ofr->duration_sec);
3161         fr->duration_nsec = ntohl(ofr->duration_nsec);
3162         fr->idle_timeout = ntohs(ofr->idle_timeout);
3163         fr->hard_timeout = ntohs(ofr->hard_timeout);
3164         fr->packet_count = ntohll(ofr->packet_count);
3165         fr->byte_count = ntohll(ofr->byte_count);
3166     } else if (raw == OFPRAW_OFPT10_FLOW_REMOVED) {
3167         const struct ofp10_flow_removed *ofr;
3168
3169         ofr = ofpbuf_pull(&b, sizeof *ofr);
3170
3171         ofputil_match_from_ofp10_match(&ofr->match, &fr->match);
3172         fr->priority = ntohs(ofr->priority);
3173         fr->cookie = ofr->cookie;
3174         fr->reason = ofr->reason;
3175         fr->table_id = 255;
3176         fr->duration_sec = ntohl(ofr->duration_sec);
3177         fr->duration_nsec = ntohl(ofr->duration_nsec);
3178         fr->idle_timeout = ntohs(ofr->idle_timeout);
3179         fr->hard_timeout = 0;
3180         fr->packet_count = ntohll(ofr->packet_count);
3181         fr->byte_count = ntohll(ofr->byte_count);
3182     } else if (raw == OFPRAW_NXT_FLOW_REMOVED) {
3183         struct nx_flow_removed *nfr;
3184         enum ofperr error;
3185
3186         nfr = ofpbuf_pull(&b, sizeof *nfr);
3187         error = nx_pull_match(&b, ntohs(nfr->match_len), &fr->match,
3188                               NULL, NULL);
3189         if (error) {
3190             return error;
3191         }
3192         if (b.size) {
3193             return OFPERR_OFPBRC_BAD_LEN;
3194         }
3195
3196         fr->priority = ntohs(nfr->priority);
3197         fr->cookie = nfr->cookie;
3198         fr->reason = nfr->reason;
3199         fr->table_id = nfr->table_id ? nfr->table_id - 1 : 255;
3200         fr->duration_sec = ntohl(nfr->duration_sec);
3201         fr->duration_nsec = ntohl(nfr->duration_nsec);
3202         fr->idle_timeout = ntohs(nfr->idle_timeout);
3203         fr->hard_timeout = 0;
3204         fr->packet_count = ntohll(nfr->packet_count);
3205         fr->byte_count = ntohll(nfr->byte_count);
3206     } else {
3207         OVS_NOT_REACHED();
3208     }
3209
3210     return 0;
3211 }
3212
3213 /* Converts abstract ofputil_flow_removed 'fr' into an OFPT_FLOW_REMOVED or
3214  * NXT_FLOW_REMOVED message 'oh' according to 'protocol', and returns the
3215  * message. */
3216 struct ofpbuf *
3217 ofputil_encode_flow_removed(const struct ofputil_flow_removed *fr,
3218                             enum ofputil_protocol protocol)
3219 {
3220     struct ofpbuf *msg;
3221     enum ofp_flow_removed_reason reason = fr->reason;
3222
3223     if (reason == OFPRR_METER_DELETE && !(protocol & OFPUTIL_P_OF14_UP)) {
3224         reason = OFPRR_DELETE;
3225     }
3226
3227     switch (protocol) {
3228     case OFPUTIL_P_OF11_STD:
3229     case OFPUTIL_P_OF12_OXM:
3230     case OFPUTIL_P_OF13_OXM:
3231     case OFPUTIL_P_OF14_OXM:
3232     case OFPUTIL_P_OF15_OXM: {
3233         struct ofp12_flow_removed *ofr;
3234
3235         msg = ofpraw_alloc_xid(OFPRAW_OFPT11_FLOW_REMOVED,
3236                                ofputil_protocol_to_ofp_version(protocol),
3237                                htonl(0),
3238                                ofputil_match_typical_len(protocol));
3239         ofr = ofpbuf_put_zeros(msg, sizeof *ofr);
3240         ofr->cookie = fr->cookie;
3241         ofr->priority = htons(fr->priority);
3242         ofr->reason = reason;
3243         ofr->table_id = fr->table_id;
3244         ofr->duration_sec = htonl(fr->duration_sec);
3245         ofr->duration_nsec = htonl(fr->duration_nsec);
3246         ofr->idle_timeout = htons(fr->idle_timeout);
3247         ofr->hard_timeout = htons(fr->hard_timeout);
3248         ofr->packet_count = htonll(fr->packet_count);
3249         ofr->byte_count = htonll(fr->byte_count);
3250         ofputil_put_ofp11_match(msg, &fr->match, protocol);
3251         break;
3252     }
3253
3254     case OFPUTIL_P_OF10_STD:
3255     case OFPUTIL_P_OF10_STD_TID: {
3256         struct ofp10_flow_removed *ofr;
3257
3258         msg = ofpraw_alloc_xid(OFPRAW_OFPT10_FLOW_REMOVED, OFP10_VERSION,
3259                                htonl(0), 0);
3260         ofr = ofpbuf_put_zeros(msg, sizeof *ofr);
3261         ofputil_match_to_ofp10_match(&fr->match, &ofr->match);
3262         ofr->cookie = fr->cookie;
3263         ofr->priority = htons(fr->priority);
3264         ofr->reason = reason;
3265         ofr->duration_sec = htonl(fr->duration_sec);
3266         ofr->duration_nsec = htonl(fr->duration_nsec);
3267         ofr->idle_timeout = htons(fr->idle_timeout);
3268         ofr->packet_count = htonll(unknown_to_zero(fr->packet_count));
3269         ofr->byte_count = htonll(unknown_to_zero(fr->byte_count));
3270         break;
3271     }
3272
3273     case OFPUTIL_P_OF10_NXM:
3274     case OFPUTIL_P_OF10_NXM_TID: {
3275         struct nx_flow_removed *nfr;
3276         int match_len;
3277
3278         msg = ofpraw_alloc_xid(OFPRAW_NXT_FLOW_REMOVED, OFP10_VERSION,
3279                                htonl(0), NXM_TYPICAL_LEN);
3280         ofpbuf_put_zeros(msg, sizeof *nfr);
3281         match_len = nx_put_match(msg, &fr->match, 0, 0);
3282
3283         nfr = msg->msg;
3284         nfr->cookie = fr->cookie;
3285         nfr->priority = htons(fr->priority);
3286         nfr->reason = reason;
3287         nfr->table_id = fr->table_id + 1;
3288         nfr->duration_sec = htonl(fr->duration_sec);
3289         nfr->duration_nsec = htonl(fr->duration_nsec);
3290         nfr->idle_timeout = htons(fr->idle_timeout);
3291         nfr->match_len = htons(match_len);
3292         nfr->packet_count = htonll(fr->packet_count);
3293         nfr->byte_count = htonll(fr->byte_count);
3294         break;
3295     }
3296
3297     default:
3298         OVS_NOT_REACHED();
3299     }
3300
3301     return msg;
3302 }
3303
3304 /* The caller has done basic initialization of '*pin'; the other output
3305  * arguments needs to be initialized. */
3306 static enum ofperr
3307 decode_nx_packet_in2(const struct ofp_header *oh,
3308                      struct ofputil_packet_in *pin,
3309                      size_t *total_len, uint32_t *buffer_id)
3310 {
3311     *total_len = 0;
3312     *buffer_id = UINT32_MAX;
3313
3314     struct ofpbuf properties;
3315     ofpbuf_use_const(&properties, oh, ntohs(oh->length));
3316     ofpraw_pull_assert(&properties);
3317
3318     while (properties.size > 0) {
3319         struct ofpbuf payload;
3320         uint64_t type;
3321
3322         enum ofperr error = ofpprop_pull(&properties, &payload, &type);
3323         if (error) {
3324             return error;
3325         }
3326
3327         switch (type) {
3328         case NXPINT_PACKET:
3329             pin->packet = payload.msg;
3330             pin->packet_len = ofpbuf_msgsize(&payload);
3331             break;
3332
3333         case NXPINT_FULL_LEN: {
3334             uint32_t u32;
3335             error = ofpprop_parse_u32(&payload, &u32);
3336             *total_len = u32;
3337             break;
3338         }
3339
3340         case NXPINT_BUFFER_ID:
3341             error = ofpprop_parse_u32(&payload, buffer_id);
3342             break;
3343
3344         case NXPINT_TABLE_ID:
3345             error = ofpprop_parse_u8(&payload, &pin->table_id);
3346             break;
3347
3348         case NXPINT_COOKIE:
3349             error = ofpprop_parse_be64(&payload, &pin->cookie);
3350             break;
3351
3352         case NXPINT_REASON: {
3353             uint8_t reason;
3354             error = ofpprop_parse_u8(&payload, &reason);
3355             pin->reason = reason;
3356             break;
3357         }
3358
3359         case NXPINT_METADATA:
3360             error = oxm_decode_match(payload.msg, ofpbuf_msgsize(&payload),
3361                                      &pin->flow_metadata);
3362             break;
3363
3364         case NXPINT_USERDATA:
3365             pin->userdata = payload.msg;
3366             pin->userdata_len = ofpbuf_msgsize(&payload);
3367             break;
3368
3369         default:
3370             error = OFPPROP_UNKNOWN(true, "NX_PACKET_IN2", type);
3371             break;
3372         }
3373         if (error) {
3374             return error;
3375         }
3376     }
3377
3378     if (!pin->packet_len) {
3379         VLOG_WARN_RL(&bad_ofmsg_rl, "NXT_PACKET_IN2 lacks packet");
3380         return OFPERR_OFPBRC_BAD_LEN;
3381     } else if (!*total_len) {
3382         *total_len = pin->packet_len;
3383     } else if (*total_len < pin->packet_len) {
3384         VLOG_WARN_RL(&bad_ofmsg_rl, "NXT_PACKET_IN2 claimed full_len < len");
3385         return OFPERR_OFPBRC_BAD_LEN;
3386     }
3387
3388     return 0;
3389 }
3390
3391 /* Decodes the packet-in message starting at 'oh' into '*pin'.  Populates
3392  * 'pin->packet' and 'pin->len' with the part of the packet actually included
3393  * in the message, and '*total_len' with the original length of the packet
3394  * (which is larger than 'packet->len' if only part of the packet was
3395  * included).  Stores the packet's buffer ID in '*buffer_id' (UINT32_MAX if it
3396  * was not buffered).
3397  *
3398  * Returns 0 if successful, otherwise an OpenFlow error code. */
3399 enum ofperr
3400 ofputil_decode_packet_in(const struct ofp_header *oh,
3401                          struct ofputil_packet_in *pin,
3402                          size_t *total_len, uint32_t *buffer_id)
3403 {
3404     memset(pin, 0, sizeof *pin);
3405     pin->cookie = OVS_BE64_MAX;
3406
3407     struct ofpbuf b = ofpbuf_const_initializer(oh, ntohs(oh->length));
3408     enum ofpraw raw = ofpraw_pull_assert(&b);
3409     if (raw == OFPRAW_OFPT13_PACKET_IN || raw == OFPRAW_OFPT12_PACKET_IN) {
3410         const struct ofp12_packet_in *opi = ofpbuf_pull(&b, sizeof *opi);
3411         const ovs_be64 *cookie = (raw == OFPRAW_OFPT13_PACKET_IN
3412                                   ? ofpbuf_pull(&b, sizeof *cookie)
3413                                   : NULL);
3414         enum ofperr error = oxm_pull_match_loose(&b, &pin->flow_metadata);
3415         if (error) {
3416             return error;
3417         }
3418
3419         if (!ofpbuf_try_pull(&b, 2)) {
3420             return OFPERR_OFPBRC_BAD_LEN;
3421         }
3422
3423         pin->reason = opi->reason;
3424         pin->table_id = opi->table_id;
3425         *buffer_id = ntohl(opi->buffer_id);
3426         *total_len = ntohs(opi->total_len);
3427         if (cookie) {
3428             pin->cookie = *cookie;
3429         }
3430
3431         pin->packet = b.data;
3432         pin->packet_len = b.size;
3433     } else if (raw == OFPRAW_OFPT10_PACKET_IN) {
3434         const struct ofp10_packet_in *opi;
3435
3436         opi = ofpbuf_pull(&b, offsetof(struct ofp10_packet_in, data));
3437
3438         pin->packet = CONST_CAST(uint8_t *, opi->data);
3439         pin->packet_len = b.size;
3440
3441         match_init_catchall(&pin->flow_metadata);
3442         match_set_in_port(&pin->flow_metadata,
3443                           u16_to_ofp(ntohs(opi->in_port)));
3444         pin->reason = opi->reason;
3445         *buffer_id = ntohl(opi->buffer_id);
3446         *total_len = ntohs(opi->total_len);
3447     } else if (raw == OFPRAW_OFPT11_PACKET_IN) {
3448         const struct ofp11_packet_in *opi;
3449         ofp_port_t in_port;
3450         enum ofperr error;
3451
3452         opi = ofpbuf_pull(&b, sizeof *opi);
3453
3454         pin->packet = b.data;
3455         pin->packet_len = b.size;
3456
3457         *buffer_id = ntohl(opi->buffer_id);
3458         error = ofputil_port_from_ofp11(opi->in_port, &in_port);
3459         if (error) {
3460             return error;
3461         }
3462         match_init_catchall(&pin->flow_metadata);
3463         match_set_in_port(&pin->flow_metadata, in_port);
3464         *total_len = ntohs(opi->total_len);
3465         pin->reason = opi->reason;
3466         pin->table_id = opi->table_id;
3467     } else if (raw == OFPRAW_NXT_PACKET_IN) {
3468         const struct nx_packet_in *npi;
3469         int error;
3470
3471         npi = ofpbuf_pull(&b, sizeof *npi);
3472         error = nx_pull_match_loose(&b, ntohs(npi->match_len),
3473                                     &pin->flow_metadata, NULL, NULL);
3474         if (error) {
3475             return error;
3476         }
3477
3478         if (!ofpbuf_try_pull(&b, 2)) {
3479             return OFPERR_OFPBRC_BAD_LEN;
3480         }
3481
3482         pin->reason = npi->reason;
3483         pin->table_id = npi->table_id;
3484         pin->cookie = npi->cookie;
3485
3486         *buffer_id = ntohl(npi->buffer_id);
3487         *total_len = ntohs(npi->total_len);
3488
3489         pin->packet = b.data;
3490         pin->packet_len = b.size;
3491     } else if (raw == OFPRAW_NXT_PACKET_IN2) {
3492         return decode_nx_packet_in2(oh, pin, total_len, buffer_id);
3493     } else {
3494         OVS_NOT_REACHED();
3495     }
3496
3497     return 0;
3498 }
3499
3500 static int
3501 encode_packet_in_reason(enum ofp_packet_in_reason reason,
3502                         enum ofp_version version)
3503 {
3504     switch (reason) {
3505     case OFPR_NO_MATCH:
3506     case OFPR_ACTION:
3507     case OFPR_INVALID_TTL:
3508         return reason;
3509
3510     case OFPR_ACTION_SET:
3511     case OFPR_GROUP:
3512     case OFPR_PACKET_OUT:
3513         return version < OFP14_VERSION ? OFPR_ACTION : reason;
3514
3515     case OFPR_EXPLICIT_MISS:
3516         return version < OFP13_VERSION ? OFPR_ACTION : OFPR_NO_MATCH;
3517
3518     case OFPR_IMPLICIT_MISS:
3519         return OFPR_NO_MATCH;
3520
3521     case OFPR_N_REASONS:
3522     default:
3523         OVS_NOT_REACHED();
3524     }
3525 }
3526
3527 static struct ofpbuf *
3528 ofputil_encode_ofp10_packet_in(const struct ofputil_packet_in *pin,
3529                                uint32_t buffer_id)
3530 {
3531     struct ofp10_packet_in *opi;
3532     struct ofpbuf *msg;
3533
3534     msg = ofpraw_alloc_xid(OFPRAW_OFPT10_PACKET_IN, OFP10_VERSION,
3535                            htonl(0), pin->packet_len);
3536     opi = ofpbuf_put_zeros(msg, offsetof(struct ofp10_packet_in, data));
3537     opi->total_len = htons(pin->packet_len);
3538     opi->in_port = htons(ofp_to_u16(pin->flow_metadata.flow.in_port.ofp_port));
3539     opi->reason = encode_packet_in_reason(pin->reason, OFP10_VERSION);
3540     opi->buffer_id = htonl(buffer_id);
3541
3542     return msg;
3543 }
3544
3545 static struct ofpbuf *
3546 ofputil_encode_nx_packet_in(const struct ofputil_packet_in *pin,
3547                             enum ofp_version version, uint32_t buffer_id)
3548 {
3549     struct nx_packet_in *npi;
3550     struct ofpbuf *msg;
3551     size_t match_len;
3552
3553     /* The final argument is just an estimate of the space required. */
3554     msg = ofpraw_alloc_xid(OFPRAW_NXT_PACKET_IN, version,
3555                            htonl(0), NXM_TYPICAL_LEN + 2 + pin->packet_len);
3556     ofpbuf_put_zeros(msg, sizeof *npi);
3557     match_len = nx_put_match(msg, &pin->flow_metadata, 0, 0);
3558     ofpbuf_put_zeros(msg, 2);
3559
3560     npi = msg->msg;
3561     npi->buffer_id = htonl(buffer_id);
3562     npi->total_len = htons(pin->packet_len);
3563     npi->reason = encode_packet_in_reason(pin->reason, version);
3564     npi->table_id = pin->table_id;
3565     npi->cookie = pin->cookie;
3566     npi->match_len = htons(match_len);
3567
3568     return msg;
3569 }
3570
3571 static struct ofpbuf *
3572 ofputil_encode_nx_packet_in2(const struct ofputil_packet_in *pin,
3573                              enum ofp_version version, uint32_t buffer_id,
3574                              size_t include_bytes)
3575 {
3576     /* 'extra' is just an estimate of the space required. */
3577     size_t extra = include_bytes + NXM_TYPICAL_LEN + 256;
3578     struct ofpbuf *msg = ofpraw_alloc_xid(OFPRAW_NXT_PACKET_IN2, version,
3579                                           htonl(0), extra);
3580
3581     /* Add packet properties. */
3582     ofpprop_put(msg, NXPINT_PACKET, pin->packet, include_bytes);
3583     if (include_bytes != pin->packet_len) {
3584         ofpprop_put_u32(msg, NXPINT_FULL_LEN, pin->packet_len);
3585     }
3586     if (buffer_id != UINT32_MAX) {
3587         ofpprop_put_u32(msg, NXPINT_BUFFER_ID, buffer_id);
3588     }
3589
3590     /* Add flow properties. */
3591     ofpprop_put_u8(msg, NXPINT_TABLE_ID, pin->table_id);
3592     if (pin->cookie != OVS_BE64_MAX) {
3593         ofpprop_put_be64(msg, NXPINT_COOKIE, pin->cookie);
3594     }
3595
3596     /* Add other properties. */
3597     ofpprop_put_u8(msg, NXPINT_REASON,
3598                    encode_packet_in_reason(pin->reason, version));
3599
3600     size_t start = ofpprop_start(msg, NXPINT_METADATA);
3601     oxm_put_raw(msg, &pin->flow_metadata, version);
3602     ofpprop_end(msg, start);
3603
3604     if (pin->userdata_len) {
3605         ofpprop_put(msg, NXPINT_USERDATA, pin->userdata, pin->userdata_len);
3606     }
3607
3608     ofpmsg_update_length(msg);
3609     return msg;
3610 }
3611
3612 static struct ofpbuf *
3613 ofputil_encode_ofp11_packet_in(const struct ofputil_packet_in *pin,
3614                                uint32_t buffer_id)
3615 {
3616     struct ofp11_packet_in *opi;
3617     struct ofpbuf *msg;
3618
3619     msg = ofpraw_alloc_xid(OFPRAW_OFPT11_PACKET_IN, OFP11_VERSION,
3620                            htonl(0), pin->packet_len);
3621     opi = ofpbuf_put_zeros(msg, sizeof *opi);
3622     opi->buffer_id = htonl(buffer_id);
3623     opi->in_port = ofputil_port_to_ofp11(
3624         pin->flow_metadata.flow.in_port.ofp_port);
3625     opi->in_phy_port = opi->in_port;
3626     opi->total_len = htons(pin->packet_len);
3627     opi->reason = encode_packet_in_reason(pin->reason, OFP11_VERSION);
3628     opi->table_id = pin->table_id;
3629
3630     return msg;
3631 }
3632
3633 static struct ofpbuf *
3634 ofputil_encode_ofp12_packet_in(const struct ofputil_packet_in *pin,
3635                                enum ofp_version version,
3636                                uint32_t buffer_id)
3637 {
3638     enum ofpraw raw = (version >= OFP13_VERSION
3639                        ? OFPRAW_OFPT13_PACKET_IN
3640                        : OFPRAW_OFPT12_PACKET_IN);
3641     struct ofpbuf *msg;
3642
3643     /* The final argument is just an estimate of the space required. */
3644     msg = ofpraw_alloc_xid(raw, version,
3645                            htonl(0), NXM_TYPICAL_LEN + 2 + pin->packet_len);
3646
3647     struct ofp12_packet_in *opi = ofpbuf_put_zeros(msg, sizeof *opi);
3648     opi->buffer_id = htonl(buffer_id);
3649     opi->total_len = htons(pin->packet_len);
3650     opi->reason = encode_packet_in_reason(pin->reason, version);
3651     opi->table_id = pin->table_id;
3652
3653     if (version >= OFP13_VERSION) {
3654         ovs_be64 cookie = pin->cookie;
3655         ofpbuf_put(msg, &cookie, sizeof cookie);
3656     }
3657
3658     oxm_put_match(msg, &pin->flow_metadata, version);
3659     ofpbuf_put_zeros(msg, 2);
3660
3661     return msg;
3662 }
3663
3664 /* Converts abstract ofputil_packet_in 'pin' into a PACKET_IN message for
3665  * 'protocol', using the packet-in format specified by 'packet_in_format'.
3666  *
3667  * If 'pkt_buf' is nonnull and 'max_len' allows the packet to be buffered, this
3668  * function will attempt to obtain a buffer ID from 'pktbuf' and truncate the
3669  * packet to 'max_len' bytes.  Otherwise, or if 'pktbuf' doesn't have a free
3670  * buffer, it will send the whole packet without buffering. */
3671 struct ofpbuf *
3672 ofputil_encode_packet_in(const struct ofputil_packet_in *pin,
3673                          enum ofputil_protocol protocol,
3674                          enum nx_packet_in_format packet_in_format,
3675                          uint16_t max_len, struct pktbuf *pktbuf)
3676 {
3677     enum ofp_version version = ofputil_protocol_to_ofp_version(protocol);
3678
3679     /* Get buffer ID. */
3680     ofp_port_t in_port = pin->flow_metadata.flow.in_port.ofp_port;
3681     uint32_t buffer_id = (max_len != OFPCML12_NO_BUFFER && pktbuf
3682                           ? pktbuf_save(pktbuf, pin->packet,
3683                                         pin->packet_len, in_port)
3684                           : UINT32_MAX);
3685
3686     /* Calculate the number of bytes of the packet to include in the
3687      * packet-in:
3688      *
3689      *    - If not buffered, the whole thing.
3690      *
3691      *    - Otherwise, no more than 'max_len' bytes. */
3692     size_t include_bytes = (buffer_id == UINT32_MAX
3693                             ? pin->packet_len
3694                             : MIN(max_len, pin->packet_len));
3695
3696     struct ofpbuf *msg;
3697     switch (packet_in_format) {
3698     case NXPIF_STANDARD:
3699         switch (protocol) {
3700         case OFPUTIL_P_OF10_STD:
3701         case OFPUTIL_P_OF10_STD_TID:
3702         case OFPUTIL_P_OF10_NXM:
3703         case OFPUTIL_P_OF10_NXM_TID:
3704             msg = ofputil_encode_ofp10_packet_in(pin, buffer_id);
3705             break;
3706
3707         case OFPUTIL_P_OF11_STD:
3708             msg = ofputil_encode_ofp11_packet_in(pin, buffer_id);
3709             break;
3710
3711         case OFPUTIL_P_OF12_OXM:
3712         case OFPUTIL_P_OF13_OXM:
3713         case OFPUTIL_P_OF14_OXM:
3714         case OFPUTIL_P_OF15_OXM:
3715             msg = ofputil_encode_ofp12_packet_in(pin, version, buffer_id);
3716             break;
3717
3718         default:
3719             OVS_NOT_REACHED();
3720         }
3721         break;
3722
3723     case NXPIF_NXT_PACKET_IN:
3724         msg = ofputil_encode_nx_packet_in(pin, version, buffer_id);
3725         break;
3726
3727     case NXPIF_NXT_PACKET_IN2:
3728         return ofputil_encode_nx_packet_in2(pin, version, buffer_id,
3729                                             include_bytes);
3730
3731     default:
3732         OVS_NOT_REACHED();
3733     }
3734
3735     ofpbuf_put(msg, pin->packet, include_bytes);
3736     ofpmsg_update_length(msg);
3737     return msg;
3738 }
3739
3740 /* Returns a string form of 'reason'.  The return value is either a statically
3741  * allocated constant string or the 'bufsize'-byte buffer 'reasonbuf'.
3742  * 'bufsize' should be at least OFPUTIL_PACKET_IN_REASON_BUFSIZE. */
3743 const char *
3744 ofputil_packet_in_reason_to_string(enum ofp_packet_in_reason reason,
3745                                    char *reasonbuf, size_t bufsize)
3746 {
3747     switch (reason) {
3748     case OFPR_NO_MATCH:
3749         return "no_match";
3750     case OFPR_ACTION:
3751         return "action";
3752     case OFPR_INVALID_TTL:
3753         return "invalid_ttl";
3754     case OFPR_ACTION_SET:
3755         return "action_set";
3756     case OFPR_GROUP:
3757         return "group";
3758     case OFPR_PACKET_OUT:
3759         return "packet_out";
3760     case OFPR_EXPLICIT_MISS:
3761     case OFPR_IMPLICIT_MISS:
3762         return "";
3763
3764     case OFPR_N_REASONS:
3765     default:
3766         snprintf(reasonbuf, bufsize, "%d", (int) reason);
3767         return reasonbuf;
3768     }
3769 }
3770
3771 bool
3772 ofputil_packet_in_reason_from_string(const char *s,
3773                                      enum ofp_packet_in_reason *reason)
3774 {
3775     int i;
3776
3777     for (i = 0; i < OFPR_N_REASONS; i++) {
3778         char reasonbuf[OFPUTIL_PACKET_IN_REASON_BUFSIZE];
3779         const char *reason_s;
3780
3781         reason_s = ofputil_packet_in_reason_to_string(i, reasonbuf,
3782                                                       sizeof reasonbuf);
3783         if (!strcasecmp(s, reason_s)) {
3784             *reason = i;
3785             return true;
3786         }
3787     }
3788     return false;
3789 }
3790
3791 /* Converts an OFPT_PACKET_OUT in 'opo' into an abstract ofputil_packet_out in
3792  * 'po'.
3793  *
3794  * Uses 'ofpacts' to store the abstract OFPACT_* version of the packet out
3795  * message's actions.  The caller must initialize 'ofpacts' and retains
3796  * ownership of it.  'po->ofpacts' will point into the 'ofpacts' buffer.
3797  *
3798  * Returns 0 if successful, otherwise an OFPERR_* value. */
3799 enum ofperr
3800 ofputil_decode_packet_out(struct ofputil_packet_out *po,
3801                           const struct ofp_header *oh,
3802                           struct ofpbuf *ofpacts)
3803 {
3804     struct ofpbuf b = ofpbuf_const_initializer(oh, ntohs(oh->length));
3805     enum ofpraw raw = ofpraw_pull_assert(&b);
3806
3807     ofpbuf_clear(ofpacts);
3808     if (raw == OFPRAW_OFPT11_PACKET_OUT) {
3809         enum ofperr error;
3810         const struct ofp11_packet_out *opo = ofpbuf_pull(&b, sizeof *opo);
3811
3812         po->buffer_id = ntohl(opo->buffer_id);
3813         error = ofputil_port_from_ofp11(opo->in_port, &po->in_port);
3814         if (error) {
3815             return error;
3816         }
3817
3818         error = ofpacts_pull_openflow_actions(&b, ntohs(opo->actions_len),
3819                                               oh->version, ofpacts);
3820         if (error) {
3821             return error;
3822         }
3823     } else if (raw == OFPRAW_OFPT10_PACKET_OUT) {
3824         enum ofperr error;
3825         const struct ofp10_packet_out *opo = ofpbuf_pull(&b, sizeof *opo);
3826
3827         po->buffer_id = ntohl(opo->buffer_id);
3828         po->in_port = u16_to_ofp(ntohs(opo->in_port));
3829
3830         error = ofpacts_pull_openflow_actions(&b, ntohs(opo->actions_len),
3831                                               oh->version, ofpacts);
3832         if (error) {
3833             return error;
3834         }
3835     } else {
3836         OVS_NOT_REACHED();
3837     }
3838
3839     if (ofp_to_u16(po->in_port) >= ofp_to_u16(OFPP_MAX)
3840         && po->in_port != OFPP_LOCAL
3841         && po->in_port != OFPP_NONE && po->in_port != OFPP_CONTROLLER) {
3842         VLOG_WARN_RL(&bad_ofmsg_rl, "packet-out has bad input port %#"PRIx16,
3843                      po->in_port);
3844         return OFPERR_OFPBRC_BAD_PORT;
3845     }
3846
3847     po->ofpacts = ofpacts->data;
3848     po->ofpacts_len = ofpacts->size;
3849
3850     if (po->buffer_id == UINT32_MAX) {
3851         po->packet = b.data;
3852         po->packet_len = b.size;
3853     } else {
3854         po->packet = NULL;
3855         po->packet_len = 0;
3856     }
3857
3858     return 0;
3859 }
3860 \f
3861 /* ofputil_phy_port */
3862
3863 /* NETDEV_F_* to and from OFPPF_* and OFPPF10_*. */
3864 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_HD    == OFPPF_10MB_HD);  /* bit 0 */
3865 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_FD    == OFPPF_10MB_FD);  /* bit 1 */
3866 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_HD   == OFPPF_100MB_HD); /* bit 2 */
3867 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_FD   == OFPPF_100MB_FD); /* bit 3 */
3868 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_HD     == OFPPF_1GB_HD);   /* bit 4 */
3869 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_FD     == OFPPF_1GB_FD);   /* bit 5 */
3870 BUILD_ASSERT_DECL((int) NETDEV_F_10GB_FD    == OFPPF_10GB_FD);  /* bit 6 */
3871
3872 /* NETDEV_F_ bits 11...15 are OFPPF10_ bits 7...11: */
3873 BUILD_ASSERT_DECL((int) NETDEV_F_COPPER == (OFPPF10_COPPER << 4));
3874 BUILD_ASSERT_DECL((int) NETDEV_F_FIBER == (OFPPF10_FIBER << 4));
3875 BUILD_ASSERT_DECL((int) NETDEV_F_AUTONEG == (OFPPF10_AUTONEG << 4));
3876 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE == (OFPPF10_PAUSE << 4));
3877 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE_ASYM == (OFPPF10_PAUSE_ASYM << 4));
3878
3879 static enum netdev_features
3880 netdev_port_features_from_ofp10(ovs_be32 ofp10_)
3881 {
3882     uint32_t ofp10 = ntohl(ofp10_);
3883     return (ofp10 & 0x7f) | ((ofp10 & 0xf80) << 4);
3884 }
3885
3886 static ovs_be32
3887 netdev_port_features_to_ofp10(enum netdev_features features)
3888 {
3889     return htonl((features & 0x7f) | ((features & 0xf800) >> 4));
3890 }
3891
3892 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_HD    == OFPPF_10MB_HD);     /* bit 0 */
3893 BUILD_ASSERT_DECL((int) NETDEV_F_10MB_FD    == OFPPF_10MB_FD);     /* bit 1 */
3894 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_HD   == OFPPF_100MB_HD);    /* bit 2 */
3895 BUILD_ASSERT_DECL((int) NETDEV_F_100MB_FD   == OFPPF_100MB_FD);    /* bit 3 */
3896 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_HD     == OFPPF_1GB_HD);      /* bit 4 */
3897 BUILD_ASSERT_DECL((int) NETDEV_F_1GB_FD     == OFPPF_1GB_FD);      /* bit 5 */
3898 BUILD_ASSERT_DECL((int) NETDEV_F_10GB_FD    == OFPPF_10GB_FD);     /* bit 6 */
3899 BUILD_ASSERT_DECL((int) NETDEV_F_40GB_FD    == OFPPF11_40GB_FD);   /* bit 7 */
3900 BUILD_ASSERT_DECL((int) NETDEV_F_100GB_FD   == OFPPF11_100GB_FD);  /* bit 8 */
3901 BUILD_ASSERT_DECL((int) NETDEV_F_1TB_FD     == OFPPF11_1TB_FD);    /* bit 9 */
3902 BUILD_ASSERT_DECL((int) NETDEV_F_OTHER      == OFPPF11_OTHER);     /* bit 10 */
3903 BUILD_ASSERT_DECL((int) NETDEV_F_COPPER     == OFPPF11_COPPER);    /* bit 11 */
3904 BUILD_ASSERT_DECL((int) NETDEV_F_FIBER      == OFPPF11_FIBER);     /* bit 12 */
3905 BUILD_ASSERT_DECL((int) NETDEV_F_AUTONEG    == OFPPF11_AUTONEG);   /* bit 13 */
3906 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE      == OFPPF11_PAUSE);     /* bit 14 */
3907 BUILD_ASSERT_DECL((int) NETDEV_F_PAUSE_ASYM == OFPPF11_PAUSE_ASYM);/* bit 15 */
3908
3909 static enum netdev_features
3910 netdev_port_features_from_ofp11(ovs_be32 ofp11)
3911 {
3912     return ntohl(ofp11) & 0xffff;
3913 }
3914
3915 static ovs_be32
3916 netdev_port_features_to_ofp11(enum netdev_features features)
3917 {
3918     return htonl(features & 0xffff);
3919 }
3920
3921 static enum ofperr
3922 ofputil_decode_ofp10_phy_port(struct ofputil_phy_port *pp,
3923                               const struct ofp10_phy_port *opp)
3924 {
3925     pp->port_no = u16_to_ofp(ntohs(opp->port_no));
3926     pp->hw_addr = opp->hw_addr;
3927     ovs_strlcpy(pp->name, opp->name, OFP_MAX_PORT_NAME_LEN);
3928
3929     pp->config = ntohl(opp->config) & OFPPC10_ALL;
3930     pp->state = ntohl(opp->state) & OFPPS10_ALL;
3931
3932     pp->curr = netdev_port_features_from_ofp10(opp->curr);
3933     pp->advertised = netdev_port_features_from_ofp10(opp->advertised);
3934     pp->supported = netdev_port_features_from_ofp10(opp->supported);
3935     pp->peer = netdev_port_features_from_ofp10(opp->peer);
3936
3937     pp->curr_speed = netdev_features_to_bps(pp->curr, 0) / 1000;
3938     pp->max_speed = netdev_features_to_bps(pp->supported, 0) / 1000;
3939
3940     return 0;
3941 }
3942
3943 static enum ofperr
3944 ofputil_decode_ofp11_port(struct ofputil_phy_port *pp,
3945                           const struct ofp11_port *op)
3946 {
3947     enum ofperr error;
3948
3949     error = ofputil_port_from_ofp11(op->port_no, &pp->port_no);
3950     if (error) {
3951         return error;
3952     }
3953     pp->hw_addr = op->hw_addr;
3954     ovs_strlcpy(pp->name, op->name, OFP_MAX_PORT_NAME_LEN);
3955
3956     pp->config = ntohl(op->config) & OFPPC11_ALL;
3957     pp->state = ntohl(op->state) & OFPPS11_ALL;
3958
3959     pp->curr = netdev_port_features_from_ofp11(op->curr);
3960     pp->advertised = netdev_port_features_from_ofp11(op->advertised);
3961     pp->supported = netdev_port_features_from_ofp11(op->supported);
3962     pp->peer = netdev_port_features_from_ofp11(op->peer);
3963
3964     pp->curr_speed = ntohl(op->curr_speed);
3965     pp->max_speed = ntohl(op->max_speed);
3966
3967     return 0;
3968 }
3969
3970 static enum ofperr
3971 parse_ofp14_port_ethernet_property(const struct ofpbuf *payload,
3972                                    struct ofputil_phy_port *pp)
3973 {
3974     struct ofp14_port_desc_prop_ethernet *eth = payload->data;
3975
3976     if (payload->size != sizeof *eth) {
3977         return OFPERR_OFPBPC_BAD_LEN;
3978     }
3979
3980     pp->curr = netdev_port_features_from_ofp11(eth->curr);
3981     pp->advertised = netdev_port_features_from_ofp11(eth->advertised);
3982     pp->supported = netdev_port_features_from_ofp11(eth->supported);
3983     pp->peer = netdev_port_features_from_ofp11(eth->peer);
3984
3985     pp->curr_speed = ntohl(eth->curr_speed);
3986     pp->max_speed = ntohl(eth->max_speed);
3987
3988     return 0;
3989 }
3990
3991 static enum ofperr
3992 ofputil_pull_ofp14_port(struct ofputil_phy_port *pp, struct ofpbuf *msg)
3993 {
3994     struct ofp14_port *op = ofpbuf_try_pull(msg, sizeof *op);
3995     if (!op) {
3996         return OFPERR_OFPBRC_BAD_LEN;
3997     }
3998
3999     size_t len = ntohs(op->length);
4000     if (len < sizeof *op || len - sizeof *op > msg->size) {
4001         return OFPERR_OFPBRC_BAD_LEN;
4002     }
4003     len -= sizeof *op;
4004
4005     enum ofperr error = ofputil_port_from_ofp11(op->port_no, &pp->port_no);
4006     if (error) {
4007         return error;
4008     }
4009     pp->hw_addr = op->hw_addr;
4010     ovs_strlcpy(pp->name, op->name, OFP_MAX_PORT_NAME_LEN);
4011
4012     pp->config = ntohl(op->config) & OFPPC11_ALL;
4013     pp->state = ntohl(op->state) & OFPPS11_ALL;
4014
4015     struct ofpbuf properties = ofpbuf_const_initializer(ofpbuf_pull(msg, len),
4016                                                         len);
4017     while (properties.size > 0) {
4018         struct ofpbuf payload;
4019         enum ofperr error;
4020         uint64_t type;
4021
4022         error = ofpprop_pull(&properties, &payload, &type);
4023         if (error) {
4024             return error;
4025         }
4026
4027         switch (type) {
4028         case OFPPDPT14_ETHERNET:
4029             error = parse_ofp14_port_ethernet_property(&payload, pp);
4030             break;
4031
4032         default:
4033             error = OFPPROP_UNKNOWN(true, "port", type);
4034             break;
4035         }
4036
4037         if (error) {
4038             return error;
4039         }
4040     }
4041
4042     return 0;
4043 }
4044
4045 static void
4046 ofputil_encode_ofp10_phy_port(const struct ofputil_phy_port *pp,
4047                               struct ofp10_phy_port *opp)
4048 {
4049     memset(opp, 0, sizeof *opp);
4050
4051     opp->port_no = htons(ofp_to_u16(pp->port_no));
4052     opp->hw_addr = pp->hw_addr;
4053     ovs_strlcpy(opp->name, pp->name, OFP_MAX_PORT_NAME_LEN);
4054
4055     opp->config = htonl(pp->config & OFPPC10_ALL);
4056     opp->state = htonl(pp->state & OFPPS10_ALL);
4057
4058     opp->curr = netdev_port_features_to_ofp10(pp->curr);
4059     opp->advertised = netdev_port_features_to_ofp10(pp->advertised);
4060     opp->supported = netdev_port_features_to_ofp10(pp->supported);
4061     opp->peer = netdev_port_features_to_ofp10(pp->peer);
4062 }
4063
4064 static void
4065 ofputil_encode_ofp11_port(const struct ofputil_phy_port *pp,
4066                           struct ofp11_port *op)
4067 {
4068     memset(op, 0, sizeof *op);
4069
4070     op->port_no = ofputil_port_to_ofp11(pp->port_no);
4071     op->hw_addr = pp->hw_addr;
4072     ovs_strlcpy(op->name, pp->name, OFP_MAX_PORT_NAME_LEN);
4073
4074     op->config = htonl(pp->config & OFPPC11_ALL);
4075     op->state = htonl(pp->state & OFPPS11_ALL);
4076
4077     op->curr = netdev_port_features_to_ofp11(pp->curr);
4078     op->advertised = netdev_port_features_to_ofp11(pp->advertised);
4079     op->supported = netdev_port_features_to_ofp11(pp->supported);
4080     op->peer = netdev_port_features_to_ofp11(pp->peer);
4081
4082     op->curr_speed = htonl(pp->curr_speed);
4083     op->max_speed = htonl(pp->max_speed);
4084 }
4085
4086 static void
4087 ofputil_put_ofp14_port(const struct ofputil_phy_port *pp,
4088                        struct ofpbuf *b)
4089 {
4090     struct ofp14_port *op;
4091     struct ofp14_port_desc_prop_ethernet *eth;
4092
4093     ofpbuf_prealloc_tailroom(b, sizeof *op + sizeof *eth);
4094
4095     op = ofpbuf_put_zeros(b, sizeof *op);
4096     op->port_no = ofputil_port_to_ofp11(pp->port_no);
4097     op->length = htons(sizeof *op + sizeof *eth);
4098     op->hw_addr = pp->hw_addr;
4099     ovs_strlcpy(op->name, pp->name, sizeof op->name);
4100     op->config = htonl(pp->config & OFPPC11_ALL);
4101     op->state = htonl(pp->state & OFPPS11_ALL);
4102
4103     eth = ofpprop_put_zeros(b, OFPPDPT14_ETHERNET, sizeof *eth);
4104     eth->curr = netdev_port_features_to_ofp11(pp->curr);
4105     eth->advertised = netdev_port_features_to_ofp11(pp->advertised);
4106     eth->supported = netdev_port_features_to_ofp11(pp->supported);
4107     eth->peer = netdev_port_features_to_ofp11(pp->peer);
4108     eth->curr_speed = htonl(pp->curr_speed);
4109     eth->max_speed = htonl(pp->max_speed);
4110 }
4111
4112 static void
4113 ofputil_put_phy_port(enum ofp_version ofp_version,
4114                      const struct ofputil_phy_port *pp, struct ofpbuf *b)
4115 {
4116     switch (ofp_version) {
4117     case OFP10_VERSION: {
4118         struct ofp10_phy_port *opp = ofpbuf_put_uninit(b, sizeof *opp);
4119         ofputil_encode_ofp10_phy_port(pp, opp);
4120         break;
4121     }
4122
4123     case OFP11_VERSION:
4124     case OFP12_VERSION:
4125     case OFP13_VERSION: {
4126         struct ofp11_port *op = ofpbuf_put_uninit(b, sizeof *op);
4127         ofputil_encode_ofp11_port(pp, op);
4128         break;
4129     }
4130
4131     case OFP14_VERSION:
4132     case OFP15_VERSION:
4133         ofputil_put_ofp14_port(pp, b);
4134         break;
4135
4136     default:
4137         OVS_NOT_REACHED();
4138     }
4139 }
4140
4141 enum ofperr
4142 ofputil_decode_port_desc_stats_request(const struct ofp_header *request,
4143                                        ofp_port_t *port)
4144 {
4145     struct ofpbuf b = ofpbuf_const_initializer(request,
4146                                                ntohs(request->length));
4147     enum ofpraw raw = ofpraw_pull_assert(&b);
4148     if (raw == OFPRAW_OFPST10_PORT_DESC_REQUEST) {
4149         *port = OFPP_ANY;
4150         return 0;
4151     } else if (raw == OFPRAW_OFPST15_PORT_DESC_REQUEST) {
4152         ovs_be32 *ofp11_port;
4153
4154         ofp11_port = ofpbuf_pull(&b, sizeof *ofp11_port);
4155         return ofputil_port_from_ofp11(*ofp11_port, port);
4156     } else {
4157         OVS_NOT_REACHED();
4158     }
4159 }
4160
4161 struct ofpbuf *
4162 ofputil_encode_port_desc_stats_request(enum ofp_version ofp_version,
4163                                        ofp_port_t port)
4164 {
4165     struct ofpbuf *request;
4166
4167     switch (ofp_version) {
4168     case OFP10_VERSION:
4169     case OFP11_VERSION:
4170     case OFP12_VERSION:
4171     case OFP13_VERSION:
4172     case OFP14_VERSION:
4173         request = ofpraw_alloc(OFPRAW_OFPST10_PORT_DESC_REQUEST,
4174                                ofp_version, 0);
4175         break;
4176     case OFP15_VERSION:{
4177         struct ofp15_port_desc_request *req;
4178         request = ofpraw_alloc(OFPRAW_OFPST15_PORT_DESC_REQUEST,
4179                                ofp_version, 0);
4180         req = ofpbuf_put_zeros(request, sizeof *req);
4181         req->port_no = ofputil_port_to_ofp11(port);
4182         break;
4183     }
4184     default:
4185         OVS_NOT_REACHED();
4186     }
4187
4188     return request;
4189 }
4190
4191 void
4192 ofputil_append_port_desc_stats_reply(const struct ofputil_phy_port *pp,
4193                                      struct ovs_list *replies)
4194 {
4195     struct ofpbuf *reply = ofpbuf_from_list(list_back(replies));
4196     size_t start_ofs = reply->size;
4197
4198     ofputil_put_phy_port(ofpmp_version(replies), pp, reply);
4199     ofpmp_postappend(replies, start_ofs);
4200 }
4201 \f
4202 /* ofputil_switch_config */
4203
4204 /* Decodes 'oh', which must be an OFPT_GET_CONFIG_REPLY or OFPT_SET_CONFIG
4205  * message, into 'config'.  Returns false if 'oh' contained any flags that
4206  * aren't specified in its version of OpenFlow, true otherwise. */
4207 static bool
4208 ofputil_decode_switch_config(const struct ofp_header *oh,
4209                              struct ofputil_switch_config *config)
4210 {
4211     struct ofpbuf b = ofpbuf_const_initializer(oh, ntohs(oh->length));
4212     ofpraw_pull_assert(&b);
4213
4214     const struct ofp_switch_config *osc = ofpbuf_pull(&b, sizeof *osc);
4215     config->frag = ntohs(osc->flags) & OFPC_FRAG_MASK;
4216     config->miss_send_len = ntohs(osc->miss_send_len);
4217
4218     ovs_be16 valid_mask = htons(OFPC_FRAG_MASK);
4219     if (oh->version < OFP13_VERSION) {
4220         const ovs_be16 ttl_bit = htons(OFPC_INVALID_TTL_TO_CONTROLLER);
4221         valid_mask |= ttl_bit;
4222         config->invalid_ttl_to_controller = (osc->flags & ttl_bit) != 0;
4223     } else {
4224         config->invalid_ttl_to_controller = -1;
4225     }
4226
4227     return !(osc->flags & ~valid_mask);
4228 }
4229
4230 void
4231 ofputil_decode_get_config_reply(const struct ofp_header *oh,
4232                                 struct ofputil_switch_config *config)
4233 {
4234     ofputil_decode_switch_config(oh, config);
4235 }
4236
4237 enum ofperr
4238 ofputil_decode_set_config(const struct ofp_header *oh,
4239                           struct ofputil_switch_config *config)
4240 {
4241     return (ofputil_decode_switch_config(oh, config)
4242             ? 0
4243             : OFPERR_OFPSCFC_BAD_FLAGS);
4244 }
4245
4246 static struct ofpbuf *
4247 ofputil_put_switch_config(const struct ofputil_switch_config *config,
4248                           struct ofpbuf *b)
4249 {
4250     const struct ofp_header *oh = b->data;
4251     struct ofp_switch_config *osc = ofpbuf_put_zeros(b, sizeof *osc);
4252     osc->flags = htons(config->frag);
4253     if (config->invalid_ttl_to_controller > 0 && oh->version < OFP13_VERSION) {
4254         osc->flags |= htons(OFPC_INVALID_TTL_TO_CONTROLLER);
4255     }
4256     osc->miss_send_len = htons(config->miss_send_len);
4257     return b;
4258 }
4259
4260 struct ofpbuf *
4261 ofputil_encode_get_config_reply(const struct ofp_header *request,
4262                                 const struct ofputil_switch_config *config)
4263 {
4264     struct ofpbuf *b = ofpraw_alloc_reply(OFPRAW_OFPT_GET_CONFIG_REPLY,
4265                                           request, 0);
4266     return ofputil_put_switch_config(config, b);
4267 }
4268
4269 struct ofpbuf *
4270 ofputil_encode_set_config(const struct ofputil_switch_config *config,
4271                           enum ofp_version version)
4272 {
4273     struct ofpbuf *b = ofpraw_alloc(OFPRAW_OFPT_SET_CONFIG, version, 0);
4274     return ofputil_put_switch_config(config, b);
4275 }
4276 \f
4277 /* ofputil_switch_features */
4278
4279 #define OFPC_COMMON (OFPC_FLOW_STATS | OFPC_TABLE_STATS | OFPC_PORT_STATS | \
4280                      OFPC_IP_REASM | OFPC_QUEUE_STATS)
4281 BUILD_ASSERT_DECL((int) OFPUTIL_C_FLOW_STATS == OFPC_FLOW_STATS);
4282 BUILD_ASSERT_DECL((int) OFPUTIL_C_TABLE_STATS == OFPC_TABLE_STATS);
4283 BUILD_ASSERT_DECL((int) OFPUTIL_C_PORT_STATS == OFPC_PORT_STATS);
4284 BUILD_ASSERT_DECL((int) OFPUTIL_C_IP_REASM == OFPC_IP_REASM);
4285 BUILD_ASSERT_DECL((int) OFPUTIL_C_QUEUE_STATS == OFPC_QUEUE_STATS);
4286 BUILD_ASSERT_DECL((int) OFPUTIL_C_ARP_MATCH_IP == OFPC_ARP_MATCH_IP);
4287
4288 static uint32_t
4289 ofputil_capabilities_mask(enum ofp_version ofp_version)
4290 {
4291     /* Handle capabilities whose bit is unique for all OpenFlow versions */
4292     switch (ofp_version) {
4293     case OFP10_VERSION:
4294     case OFP11_VERSION:
4295         return OFPC_COMMON | OFPC_ARP_MATCH_IP;
4296     case OFP12_VERSION:
4297     case OFP13_VERSION:
4298     case OFP14_VERSION:
4299     case OFP15_VERSION:
4300         return OFPC_COMMON | OFPC12_PORT_BLOCKED;
4301     default:
4302         /* Caller needs to check osf->header.version itself */
4303         return 0;
4304     }
4305 }
4306
4307 /* Pulls an OpenFlow "switch_features" structure from 'b' and decodes it into
4308  * an abstract representation in '*features', readying 'b' to iterate over the
4309  * OpenFlow port structures following 'osf' with later calls to
4310  * ofputil_pull_phy_port().  Returns 0 if successful, otherwise an OFPERR_*
4311  * value.  */
4312 enum ofperr
4313 ofputil_pull_switch_features(struct ofpbuf *b,
4314                              struct ofputil_switch_features *features)
4315 {
4316     const struct ofp_header *oh = b->data;
4317     enum ofpraw raw = ofpraw_pull_assert(b);
4318     const struct ofp_switch_features *osf = ofpbuf_pull(b, sizeof *osf);
4319     features->datapath_id = ntohll(osf->datapath_id);
4320     features->n_buffers = ntohl(osf->n_buffers);
4321     features->n_tables = osf->n_tables;
4322     features->auxiliary_id = 0;
4323
4324     features->capabilities = ntohl(osf->capabilities) &
4325         ofputil_capabilities_mask(oh->version);
4326
4327     if (raw == OFPRAW_OFPT10_FEATURES_REPLY) {
4328         if (osf->capabilities & htonl(OFPC10_STP)) {
4329             features->capabilities |= OFPUTIL_C_STP;
4330         }
4331         features->ofpacts = ofpact_bitmap_from_openflow(osf->actions,
4332                                                         OFP10_VERSION);
4333     } else if (raw == OFPRAW_OFPT11_FEATURES_REPLY
4334                || raw == OFPRAW_OFPT13_FEATURES_REPLY) {
4335         if (osf->capabilities & htonl(OFPC11_GROUP_STATS)) {
4336             features->capabilities |= OFPUTIL_C_GROUP_STATS;
4337         }
4338         features->ofpacts = 0;
4339         if (raw == OFPRAW_OFPT13_FEATURES_REPLY) {
4340             features->auxiliary_id = osf->auxiliary_id;
4341         }
4342     } else {
4343         return OFPERR_OFPBRC_BAD_VERSION;
4344     }
4345
4346     return 0;
4347 }
4348
4349 /* In OpenFlow 1.0, 1.1, and 1.2, an OFPT_FEATURES_REPLY message lists all the
4350  * switch's ports, unless there are too many to fit.  In OpenFlow 1.3 and
4351  * later, an OFPT_FEATURES_REPLY does not list ports at all.
4352  *
4353  * Given a buffer 'b' that contains a Features Reply message, this message
4354  * checks if it contains a complete list of the switch's ports.  Returns true,
4355  * if so.  Returns false if the list is missing (OF1.3+) or incomplete
4356  * (OF1.0/1.1/1.2), and in the latter case removes all of the ports from the
4357  * message.
4358  *
4359  * When this function returns false, the caller should send an OFPST_PORT_DESC
4360  * stats request to get the ports. */
4361 bool
4362 ofputil_switch_features_has_ports(struct ofpbuf *b)
4363 {
4364     struct ofp_header *oh = b->data;
4365     size_t phy_port_size;
4366
4367     if (oh->version >= OFP13_VERSION) {
4368         /* OpenFlow 1.3+ never has ports in the feature reply. */
4369         return false;
4370     }
4371
4372     phy_port_size = (oh->version == OFP10_VERSION
4373                      ? sizeof(struct ofp10_phy_port)
4374                      : sizeof(struct ofp11_port));
4375     if (ntohs(oh->length) + phy_port_size <= UINT16_MAX) {
4376         /* There's room for additional ports in the feature reply.
4377          * Assume that the list is complete. */
4378         return true;
4379     }
4380
4381     /* The feature reply has no room for more ports.  Probably the list is
4382      * truncated.  Drop the ports and tell the caller to retrieve them with
4383      * OFPST_PORT_DESC. */
4384     b->size = sizeof *oh + sizeof(struct ofp_switch_features);
4385     ofpmsg_update_length(b);
4386     return false;
4387 }
4388
4389 /* Returns a buffer owned by the caller that encodes 'features' in the format
4390  * required by 'protocol' with the given 'xid'.  The caller should append port
4391  * information to the buffer with subsequent calls to
4392  * ofputil_put_switch_features_port(). */
4393 struct ofpbuf *
4394 ofputil_encode_switch_features(const struct ofputil_switch_features *features,
4395                                enum ofputil_protocol protocol, ovs_be32 xid)
4396 {
4397     struct ofp_switch_features *osf;
4398     struct ofpbuf *b;
4399     enum ofp_version version;
4400     enum ofpraw raw;
4401
4402     version = ofputil_protocol_to_ofp_version(protocol);
4403     switch (version) {
4404     case OFP10_VERSION:
4405         raw = OFPRAW_OFPT10_FEATURES_REPLY;
4406         break;
4407     case OFP11_VERSION:
4408     case OFP12_VERSION:
4409         raw = OFPRAW_OFPT11_FEATURES_REPLY;
4410         break;
4411     case OFP13_VERSION:
4412     case OFP14_VERSION:
4413     case OFP15_VERSION:
4414         raw = OFPRAW_OFPT13_FEATURES_REPLY;
4415         break;
4416     default:
4417         OVS_NOT_REACHED();
4418     }
4419     b = ofpraw_alloc_xid(raw, version, xid, 0);
4420     osf = ofpbuf_put_zeros(b, sizeof *osf);
4421     osf->datapath_id = htonll(features->datapath_id);
4422     osf->n_buffers = htonl(features->n_buffers);
4423     osf->n_tables = features->n_tables;
4424
4425     osf->capabilities = htonl(features->capabilities & OFPC_COMMON);
4426     osf->capabilities = htonl(features->capabilities &
4427                               ofputil_capabilities_mask(version));
4428     switch (version) {
4429     case OFP10_VERSION:
4430         if (features->capabilities & OFPUTIL_C_STP) {
4431             osf->capabilities |= htonl(OFPC10_STP);
4432         }
4433         osf->actions = ofpact_bitmap_to_openflow(features->ofpacts,
4434                                                  OFP10_VERSION);
4435         break;
4436     case OFP13_VERSION:
4437     case OFP14_VERSION:
4438     case OFP15_VERSION:
4439         osf->auxiliary_id = features->auxiliary_id;
4440         /* fall through */
4441     case OFP11_VERSION:
4442     case OFP12_VERSION:
4443         if (features->capabilities & OFPUTIL_C_GROUP_STATS) {
4444             osf->capabilities |= htonl(OFPC11_GROUP_STATS);
4445         }
4446         break;
4447     default:
4448         OVS_NOT_REACHED();
4449     }
4450
4451     return b;
4452 }
4453
4454 /* Encodes 'pp' into the format required by the switch_features message already
4455  * in 'b', which should have been returned by ofputil_encode_switch_features(),
4456  * and appends the encoded version to 'b'. */
4457 void
4458 ofputil_put_switch_features_port(const struct ofputil_phy_port *pp,
4459                                  struct ofpbuf *b)
4460 {
4461     const struct ofp_header *oh = b->data;
4462
4463     if (oh->version < OFP13_VERSION) {
4464         /* Try adding a port description to the message, but drop it again if
4465          * the buffer overflows.  (This possibility for overflow is why
4466          * OpenFlow 1.3+ moved port descriptions into a multipart message.)  */
4467         size_t start_ofs = b->size;
4468         ofputil_put_phy_port(oh->version, pp, b);
4469         if (b->size > UINT16_MAX) {
4470             b->size = start_ofs;
4471         }
4472     }
4473 }
4474 \f
4475 /* ofputil_port_status */
4476
4477 /* Decodes the OpenFlow "port status" message in '*ops' into an abstract form
4478  * in '*ps'.  Returns 0 if successful, otherwise an OFPERR_* value. */
4479 enum ofperr
4480 ofputil_decode_port_status(const struct ofp_header *oh,
4481                            struct ofputil_port_status *ps)
4482 {
4483     struct ofpbuf b = ofpbuf_const_initializer(oh, ntohs(oh->length));
4484     ofpraw_pull_assert(&b);
4485
4486     const struct ofp_port_status *ops = ofpbuf_pull(&b, sizeof *ops);
4487     if (ops->reason != OFPPR_ADD &&
4488         ops->reason != OFPPR_DELETE &&
4489         ops->reason != OFPPR_MODIFY) {
4490         return OFPERR_NXBRC_BAD_REASON;
4491     }
4492     ps->reason = ops->reason;
4493
4494     int retval = ofputil_pull_phy_port(oh->version, &b, &ps->desc);
4495     ovs_assert(retval != EOF);
4496     return retval;
4497 }
4498
4499 /* Converts the abstract form of a "port status" message in '*ps' into an
4500  * OpenFlow message suitable for 'protocol', and returns that encoded form in
4501  * a buffer owned by the caller. */
4502 struct ofpbuf *
4503 ofputil_encode_port_status(const struct ofputil_port_status *ps,
4504                            enum ofputil_protocol protocol)
4505 {
4506     struct ofp_port_status *ops;
4507     struct ofpbuf *b;
4508     enum ofp_version version;
4509     enum ofpraw raw;
4510
4511     version = ofputil_protocol_to_ofp_version(protocol);
4512     switch (version) {
4513     case OFP10_VERSION:
4514         raw = OFPRAW_OFPT10_PORT_STATUS;
4515         break;
4516
4517     case OFP11_VERSION:
4518     case OFP12_VERSION:
4519     case OFP13_VERSION:
4520         raw = OFPRAW_OFPT11_PORT_STATUS;
4521         break;
4522
4523     case OFP14_VERSION:
4524     case OFP15_VERSION:
4525         raw = OFPRAW_OFPT14_PORT_STATUS;
4526         break;
4527
4528     default:
4529         OVS_NOT_REACHED();
4530     }
4531
4532     b = ofpraw_alloc_xid(raw, version, htonl(0), 0);
4533     ops = ofpbuf_put_zeros(b, sizeof *ops);
4534     ops->reason = ps->reason;
4535     ofputil_put_phy_port(version, &ps->desc, b);
4536     ofpmsg_update_length(b);
4537     return b;
4538 }
4539
4540 /* ofputil_port_mod */
4541
4542 static enum ofperr
4543 parse_port_mod_ethernet_property(struct ofpbuf *property,
4544                                  struct ofputil_port_mod *pm)
4545 {
4546     ovs_be32 advertise;
4547     enum ofperr error;
4548
4549     error = ofpprop_parse_be32(property, &advertise);
4550     if (!error) {
4551         pm->advertise = netdev_port_features_from_ofp11(advertise);
4552     }
4553     return error;
4554 }
4555
4556 /* Decodes the OpenFlow "port mod" message in '*oh' into an abstract form in
4557  * '*pm'.  Returns 0 if successful, otherwise an OFPERR_* value. */
4558 enum ofperr
4559 ofputil_decode_port_mod(const struct ofp_header *oh,
4560                         struct ofputil_port_mod *pm, bool loose)
4561 {
4562     struct ofpbuf b = ofpbuf_const_initializer(oh, ntohs(oh->length));
4563     enum ofpraw raw = ofpraw_pull_assert(&b);
4564     if (raw == OFPRAW_OFPT10_PORT_MOD) {
4565         const struct ofp10_port_mod *opm = b.data;
4566
4567         pm->port_no = u16_to_ofp(ntohs(opm->port_no));
4568         pm->hw_addr = opm->hw_addr;
4569         pm->config = ntohl(opm->config) & OFPPC10_ALL;
4570         pm->mask = ntohl(opm->mask) & OFPPC10_ALL;
4571         pm->advertise = netdev_port_features_from_ofp10(opm->advertise);
4572     } else if (raw == OFPRAW_OFPT11_PORT_MOD) {
4573         const struct ofp11_port_mod *opm = b.data;
4574         enum ofperr error;
4575
4576         error = ofputil_port_from_ofp11(opm->port_no, &pm->port_no);
4577         if (error) {
4578             return error;
4579         }
4580
4581         pm->hw_addr = opm->hw_addr;
4582         pm->config = ntohl(opm->config) & OFPPC11_ALL;
4583         pm->mask = ntohl(opm->mask) & OFPPC11_ALL;
4584         pm->advertise = netdev_port_features_from_ofp11(opm->advertise);
4585     } else if (raw == OFPRAW_OFPT14_PORT_MOD) {
4586         const struct ofp14_port_mod *opm = ofpbuf_pull(&b, sizeof *opm);
4587         enum ofperr error;
4588
4589         memset(pm, 0, sizeof *pm);
4590
4591         error = ofputil_port_from_ofp11(opm->port_no, &pm->port_no);
4592         if (error) {
4593             return error;
4594         }
4595
4596         pm->hw_addr = opm->hw_addr;
4597         pm->config = ntohl(opm->config) & OFPPC11_ALL;
4598         pm->mask = ntohl(opm->mask) & OFPPC11_ALL;
4599
4600         while (b.size > 0) {
4601             struct ofpbuf property;
4602             enum ofperr error;
4603             uint64_t type;
4604
4605             error = ofpprop_pull(&b, &property, &type);
4606             if (error) {
4607                 return error;
4608             }
4609
4610             switch (type) {
4611             case OFPPMPT14_ETHERNET:
4612                 error = parse_port_mod_ethernet_property(&property, pm);
4613                 break;
4614
4615             default:
4616                 error = OFPPROP_UNKNOWN(loose, "port_mod", type);
4617                 break;
4618             }
4619
4620             if (error) {
4621                 return error;
4622             }
4623         }
4624     } else {
4625         return OFPERR_OFPBRC_BAD_TYPE;
4626     }
4627
4628     pm->config &= pm->mask;
4629     return 0;
4630 }
4631
4632 /* Converts the abstract form of a "port mod" message in '*pm' into an OpenFlow
4633  * message suitable for 'protocol', and returns that encoded form in a buffer
4634  * owned by the caller. */
4635 struct ofpbuf *
4636 ofputil_encode_port_mod(const struct ofputil_port_mod *pm,
4637                         enum ofputil_protocol protocol)
4638 {
4639     enum ofp_version ofp_version = ofputil_protocol_to_ofp_version(protocol);
4640     struct ofpbuf *b;
4641
4642     switch (ofp_version) {
4643     case OFP10_VERSION: {
4644         struct ofp10_port_mod *opm;
4645
4646         b = ofpraw_alloc(OFPRAW_OFPT10_PORT_MOD, ofp_version, 0);
4647         opm = ofpbuf_put_zeros(b, sizeof *opm);
4648         opm->port_no = htons(ofp_to_u16(pm->port_no));
4649         opm->hw_addr = pm->hw_addr;
4650         opm->config = htonl(pm->config & OFPPC10_ALL);
4651         opm->mask = htonl(pm->mask & OFPPC10_ALL);
4652         opm->advertise = netdev_port_features_to_ofp10(pm->advertise);
4653         break;
4654     }
4655
4656     case OFP11_VERSION:
4657     case OFP12_VERSION:
4658     case OFP13_VERSION: {
4659         struct ofp11_port_mod *opm;
4660
4661         b = ofpraw_alloc(OFPRAW_OFPT11_PORT_MOD, ofp_version, 0);
4662         opm = ofpbuf_put_zeros(b, sizeof *opm);
4663         opm->port_no = ofputil_port_to_ofp11(pm->port_no);
4664         opm->hw_addr = pm->hw_addr;
4665         opm->config = htonl(pm->config & OFPPC11_ALL);
4666         opm->mask = htonl(pm->mask & OFPPC11_ALL);
4667         opm->advertise = netdev_port_features_to_ofp11(pm->advertise);
4668         break;
4669     }
4670     case OFP14_VERSION:
4671     case OFP15_VERSION: {
4672         struct ofp14_port_mod *opm;
4673
4674         b = ofpraw_alloc(OFPRAW_OFPT14_PORT_MOD, ofp_version, 0);
4675         opm = ofpbuf_put_zeros(b, sizeof *opm);
4676         opm->port_no = ofputil_port_to_ofp11(pm->port_no);
4677         opm->hw_addr = pm->hw_addr;
4678         opm->config = htonl(pm->config & OFPPC11_ALL);
4679         opm->mask = htonl(pm->mask & OFPPC11_ALL);
4680
4681         if (pm->advertise) {
4682             ofpprop_put_be32(b, OFPPMPT14_ETHERNET,
4683                              netdev_port_features_to_ofp11(pm->advertise));
4684         }
4685         break;
4686     }
4687     default:
4688         OVS_NOT_REACHED();
4689     }
4690
4691     return b;
4692 }
4693 \f
4694 /* Table features. */
4695
4696 static enum ofperr
4697 pull_table_feature_property(struct ofpbuf *msg, struct ofpbuf *payload,
4698                             uint64_t *typep)
4699 {
4700     enum ofperr error;
4701
4702     error = ofpprop_pull(msg, payload, typep);
4703     if (payload && !error) {
4704         ofpbuf_pull(payload, (char *)payload->msg - (char *)payload->header);
4705     }
4706     return error;
4707 }
4708
4709 static enum ofperr
4710 parse_action_bitmap(struct ofpbuf *payload, enum ofp_version ofp_version,
4711                     uint64_t *ofpacts)
4712 {
4713     uint32_t types = 0;
4714
4715     while (payload->size > 0) {
4716         enum ofperr error;
4717         uint64_t type;
4718
4719         error = ofpprop_pull__(payload, NULL, 1, 0x10000, &type);
4720         if (error) {
4721             return error;
4722         }
4723         if (type < CHAR_BIT * sizeof types) {
4724             types |= 1u << type;
4725         }
4726     }
4727
4728     *ofpacts = ofpact_bitmap_from_openflow(htonl(types), ofp_version);
4729     return 0;
4730 }
4731
4732 static enum ofperr
4733 parse_instruction_ids(struct ofpbuf *payload, bool loose, uint32_t *insts)
4734 {
4735     *insts = 0;
4736     while (payload->size > 0) {
4737         enum ovs_instruction_type inst;
4738         enum ofperr error;
4739         uint64_t ofpit;
4740
4741         /* OF1.3 and OF1.4 aren't clear about padding in the instruction IDs.
4742          * It seems clear that they aren't padded to 8 bytes, though, because
4743          * both standards say that "non-experimenter instructions are 4 bytes"
4744          * and do not mention any padding before the first instruction ID.
4745          * (There wouldn't be any point in padding to 8 bytes if the IDs were
4746          * aligned on an odd 4-byte boundary.)
4747          *
4748          * Anyway, we just assume they're all glommed together on byte
4749          * boundaries. */
4750         error = ofpprop_pull__(payload, NULL, 1, 0x10000, &ofpit);
4751         if (error) {
4752             return error;
4753         }
4754
4755         error = ovs_instruction_type_from_inst_type(&inst, ofpit);
4756         if (!error) {
4757             *insts |= 1u << inst;
4758         } else if (!loose) {
4759             return error;
4760         }
4761     }
4762     return 0;
4763 }
4764
4765 static enum ofperr
4766 parse_table_features_next_table(struct ofpbuf *payload,
4767                                 unsigned long int *next_tables)
4768 {
4769     size_t i;
4770
4771     memset(next_tables, 0, bitmap_n_bytes(255));
4772     for (i = 0; i < payload->size; i++) {
4773         uint8_t id = ((const uint8_t *) payload->data)[i];
4774         if (id >= 255) {
4775             return OFPERR_OFPBPC_BAD_VALUE;
4776         }
4777         bitmap_set1(next_tables, id);
4778     }
4779     return 0;
4780 }
4781
4782 static enum ofperr
4783 parse_oxms(struct ofpbuf *payload, bool loose,
4784            struct mf_bitmap *exactp, struct mf_bitmap *maskedp)
4785 {
4786     struct mf_bitmap exact = MF_BITMAP_INITIALIZER;
4787     struct mf_bitmap masked = MF_BITMAP_INITIALIZER;
4788
4789     while (payload->size > 0) {
4790         const struct mf_field *field;
4791         enum ofperr error;
4792         bool hasmask;
4793
4794         error = nx_pull_header(payload, &field, &hasmask);
4795         if (!error) {
4796             bitmap_set1(hasmask ? masked.bm : exact.bm, field->id);
4797         } else if (error != OFPERR_OFPBMC_BAD_FIELD || !loose) {
4798             return error;
4799         }
4800     }
4801     if (exactp) {
4802         *exactp = exact;
4803     } else if (!bitmap_is_all_zeros(exact.bm, MFF_N_IDS)) {
4804         return OFPERR_OFPBMC_BAD_MASK;
4805     }
4806     if (maskedp) {
4807         *maskedp = masked;
4808     } else if (!bitmap_is_all_zeros(masked.bm, MFF_N_IDS)) {
4809         return OFPERR_OFPBMC_BAD_MASK;
4810     }
4811     return 0;
4812 }
4813
4814 /* Converts an OFPMP_TABLE_FEATURES request or reply in 'msg' into an abstract
4815  * ofputil_table_features in 'tf'.
4816  *
4817  * If 'loose' is true, this function ignores properties and values that it does
4818  * not understand, as a controller would want to do when interpreting
4819  * capabilities provided by a switch.  If 'loose' is false, this function
4820  * treats unknown properties and values as an error, as a switch would want to
4821  * do when interpreting a configuration request made by a controller.
4822  *
4823  * A single OpenFlow message can specify features for multiple tables.  Calling
4824  * this function multiple times for a single 'msg' iterates through the tables
4825  * in the message.  The caller must initially leave 'msg''s layer pointers null
4826  * and not modify them between calls.
4827  *
4828  * Returns 0 if successful, EOF if no tables were left in this 'msg', otherwise
4829  * a positive "enum ofperr" value. */
4830 int
4831 ofputil_decode_table_features(struct ofpbuf *msg,
4832                               struct ofputil_table_features *tf, bool loose)
4833 {
4834     memset(tf, 0, sizeof *tf);
4835
4836     if (!msg->header) {
4837         ofpraw_pull_assert(msg);
4838     }
4839
4840     if (!msg->size) {
4841         return EOF;
4842     }
4843
4844     const struct ofp_header *oh = msg->header;
4845     struct ofp13_table_features *otf = msg->data;
4846     if (msg->size < sizeof *otf) {
4847         return OFPERR_OFPBPC_BAD_LEN;
4848     }
4849
4850     unsigned int len = ntohs(otf->length);
4851     if (len < sizeof *otf || len % 8 || len > msg->size) {
4852         return OFPERR_OFPBPC_BAD_LEN;
4853     }
4854
4855     tf->table_id = otf->table_id;
4856     if (tf->table_id == OFPTT_ALL) {
4857         return OFPERR_OFPTFFC_BAD_TABLE;
4858     }
4859
4860     ovs_strlcpy(tf->name, otf->name, OFP_MAX_TABLE_NAME_LEN);
4861     tf->metadata_match = otf->metadata_match;
4862     tf->metadata_write = otf->metadata_write;
4863     tf->miss_config = OFPUTIL_TABLE_MISS_DEFAULT;
4864     if (oh->version >= OFP14_VERSION) {
4865         uint32_t caps = ntohl(otf->capabilities);
4866         tf->supports_eviction = (caps & OFPTC14_EVICTION) != 0;
4867         tf->supports_vacancy_events = (caps & OFPTC14_VACANCY_EVENTS) != 0;
4868     } else {
4869         tf->supports_eviction = -1;
4870         tf->supports_vacancy_events = -1;
4871     }
4872     tf->max_entries = ntohl(otf->max_entries);
4873
4874     struct ofpbuf properties = ofpbuf_const_initializer(ofpbuf_pull(msg, len),
4875                                                         len);
4876     ofpbuf_pull(&properties, sizeof *otf);
4877     while (properties.size > 0) {
4878         struct ofpbuf payload;
4879         enum ofperr error;
4880         uint64_t type;
4881
4882         error = pull_table_feature_property(&properties, &payload, &type);
4883         if (error) {
4884             return error;
4885         }
4886
4887         switch ((enum ofp13_table_feature_prop_type) type) {
4888         case OFPTFPT13_INSTRUCTIONS:
4889             error = parse_instruction_ids(&payload, loose,
4890                                           &tf->nonmiss.instructions);
4891             break;
4892         case OFPTFPT13_INSTRUCTIONS_MISS:
4893             error = parse_instruction_ids(&payload, loose,
4894                                           &tf->miss.instructions);
4895             break;
4896
4897         case OFPTFPT13_NEXT_TABLES:
4898             error = parse_table_features_next_table(&payload,
4899                                                     tf->nonmiss.next);
4900             break;
4901         case OFPTFPT13_NEXT_TABLES_MISS:
4902             error = parse_table_features_next_table(&payload, tf->miss.next);
4903             break;
4904
4905         case OFPTFPT13_WRITE_ACTIONS:
4906             error = parse_action_bitmap(&payload, oh->version,
4907                                         &tf->nonmiss.write.ofpacts);
4908             break;
4909         case OFPTFPT13_WRITE_ACTIONS_MISS:
4910             error = parse_action_bitmap(&payload, oh->version,
4911                                         &tf->miss.write.ofpacts);
4912             break;
4913
4914         case OFPTFPT13_APPLY_ACTIONS:
4915             error = parse_action_bitmap(&payload, oh->version,
4916                                         &tf->nonmiss.apply.ofpacts);
4917             break;
4918         case OFPTFPT13_APPLY_ACTIONS_MISS:
4919             error = parse_action_bitmap(&payload, oh->version,
4920                                         &tf->miss.apply.ofpacts);
4921             break;
4922
4923         case OFPTFPT13_MATCH:
4924             error = parse_oxms(&payload, loose, &tf->match, &tf->mask);
4925             break;
4926         case OFPTFPT13_WILDCARDS:
4927             error = parse_oxms(&payload, loose, &tf->wildcard, NULL);
4928             break;
4929
4930         case OFPTFPT13_WRITE_SETFIELD:
4931             error = parse_oxms(&payload, loose,
4932                                &tf->nonmiss.write.set_fields, NULL);
4933             break;
4934         case OFPTFPT13_WRITE_SETFIELD_MISS:
4935             error = parse_oxms(&payload, loose,
4936                                &tf->miss.write.set_fields, NULL);
4937             break;
4938         case OFPTFPT13_APPLY_SETFIELD:
4939             error = parse_oxms(&payload, loose,
4940                                &tf->nonmiss.apply.set_fields, NULL);
4941             break;
4942         case OFPTFPT13_APPLY_SETFIELD_MISS:
4943             error = parse_oxms(&payload, loose,
4944                                &tf->miss.apply.set_fields, NULL);
4945             break;
4946
4947         case OFPTFPT13_EXPERIMENTER:
4948         case OFPTFPT13_EXPERIMENTER_MISS:
4949         default:
4950             error = OFPPROP_UNKNOWN(loose, "table features", type);
4951             break;
4952         }
4953         if (error) {
4954             return error;
4955         }
4956     }
4957
4958     /* Fix inconsistencies:
4959      *
4960      *     - Turn on 'match' bits that are set in 'mask', because maskable
4961      *       fields are matchable.
4962      *
4963      *     - Turn on 'wildcard' bits that are set in 'mask', because a field
4964      *       that is arbitrarily maskable can be wildcarded entirely.
4965      *
4966      *     - Turn off 'wildcard' bits that are not in 'match', because a field
4967      *       must be matchable for it to be meaningfully wildcarded. */
4968     bitmap_or(tf->match.bm, tf->mask.bm, MFF_N_IDS);
4969     bitmap_or(tf->wildcard.bm, tf->mask.bm, MFF_N_IDS);
4970     bitmap_and(tf->wildcard.bm, tf->match.bm, MFF_N_IDS);
4971
4972     return 0;
4973 }
4974
4975 /* Encodes and returns a request to obtain the table features of a switch.
4976  * The message is encoded for OpenFlow version 'ofp_version'. */
4977 struct ofpbuf *
4978 ofputil_encode_table_features_request(enum ofp_version ofp_version)
4979 {
4980     struct ofpbuf *request = NULL;
4981
4982     switch (ofp_version) {
4983     case OFP10_VERSION:
4984     case OFP11_VERSION:
4985     case OFP12_VERSION:
4986         ovs_fatal(0, "dump-table-features needs OpenFlow 1.3 or later "
4987                      "(\'-O OpenFlow13\')");
4988     case OFP13_VERSION:
4989     case OFP14_VERSION:
4990     case OFP15_VERSION:
4991         request = ofpraw_alloc(OFPRAW_OFPST13_TABLE_FEATURES_REQUEST,
4992                                ofp_version, 0);
4993         break;
4994     default:
4995         OVS_NOT_REACHED();
4996     }
4997
4998     return request;
4999 }
5000
5001 static void
5002 put_fields_property(struct ofpbuf *reply,
5003                     const struct mf_bitmap *fields,
5004                     const struct mf_bitmap *masks,
5005                     enum ofp13_table_feature_prop_type property,
5006                     enum ofp_version version)
5007 {
5008     size_t start_ofs;
5009     int field;
5010
5011     start_ofs = ofpprop_start(reply, property);
5012     BITMAP_FOR_EACH_1 (field, MFF_N_IDS, fields->bm) {
5013         nx_put_header(reply, field, version,
5014                       masks && bitmap_is_set(masks->bm, field));
5015     }
5016     ofpprop_end(reply, start_ofs);
5017 }
5018
5019 static void
5020 put_table_action_features(struct ofpbuf *reply,
5021                           const struct ofputil_table_action_features *taf,
5022                           enum ofp13_table_feature_prop_type actions_type,
5023                           enum ofp13_table_feature_prop_type set_fields_type,
5024                           int miss_offset, enum ofp_version version)
5025 {
5026     ofpprop_put_bitmap(reply, actions_type + miss_offset,
5027                        ntohl(ofpact_bitmap_to_openflow(taf->ofpacts,
5028                                                        version)));
5029     put_fields_property(reply, &taf->set_fields, NULL,
5030                         set_fields_type + miss_offset, version);
5031 }
5032
5033 static void
5034 put_table_instruction_features(
5035     struct ofpbuf *reply, const struct ofputil_table_instruction_features *tif,
5036     int miss_offset, enum ofp_version version)
5037 {
5038     size_t start_ofs;
5039     uint8_t table_id;
5040
5041     ofpprop_put_bitmap(reply, OFPTFPT13_INSTRUCTIONS + miss_offset,
5042                        ntohl(ovsinst_bitmap_to_openflow(tif->instructions,
5043                                                         version)));
5044
5045     start_ofs = ofpprop_start(reply, OFPTFPT13_NEXT_TABLES + miss_offset);
5046     BITMAP_FOR_EACH_1 (table_id, 255, tif->next) {
5047         ofpbuf_put(reply, &table_id, 1);
5048     }
5049     ofpprop_end(reply, start_ofs);
5050
5051     put_table_action_features(reply, &tif->write,
5052                               OFPTFPT13_WRITE_ACTIONS,
5053                               OFPTFPT13_WRITE_SETFIELD, miss_offset, version);
5054     put_table_action_features(reply, &tif->apply,
5055                               OFPTFPT13_APPLY_ACTIONS,
5056                               OFPTFPT13_APPLY_SETFIELD, miss_offset, version);
5057 }
5058
5059 void
5060 ofputil_append_table_features_reply(const struct ofputil_table_features *tf,
5061                                     struct ovs_list *replies)
5062 {
5063     struct ofpbuf *reply = ofpbuf_from_list(list_back(replies));
5064     enum ofp_version version = ofpmp_version(replies);
5065     size_t start_ofs = reply->size;
5066     struct ofp13_table_features *otf;
5067
5068     otf = ofpbuf_put_zeros(reply, sizeof *otf);
5069     otf->table_id = tf->table_id;
5070     ovs_strlcpy(otf->name, tf->name, sizeof otf->name);
5071     otf->metadata_match = tf->metadata_match;
5072     otf->metadata_write = tf->metadata_write;
5073     if (version >= OFP14_VERSION) {
5074         if (tf->supports_eviction) {
5075             otf->capabilities |= htonl(OFPTC14_EVICTION);
5076         }
5077         if (tf->supports_vacancy_events) {
5078             otf->capabilities |= htonl(OFPTC14_VACANCY_EVENTS);
5079         }
5080     }
5081     otf->max_entries = htonl(tf->max_entries);
5082
5083     put_table_instruction_features(reply, &tf->nonmiss, 0, version);
5084     put_table_instruction_features(reply, &tf->miss, 1, version);
5085
5086     put_fields_property(reply, &tf->match, &tf->mask,
5087                         OFPTFPT13_MATCH, version);
5088     put_fields_property(reply, &tf->wildcard, NULL,
5089                         OFPTFPT13_WILDCARDS, version);
5090
5091     otf = ofpbuf_at_assert(reply, start_ofs, sizeof *otf);
5092     otf->length = htons(reply->size - start_ofs);
5093     ofpmp_postappend(replies, start_ofs);
5094 }
5095
5096 static enum ofperr
5097 parse_table_desc_vacancy_property(struct ofpbuf *property,
5098                                   struct ofputil_table_desc *td)
5099 {
5100     struct ofp14_table_mod_prop_vacancy *otv = property->data;
5101
5102     if (property->size != sizeof *otv) {
5103         return OFPERR_OFPBPC_BAD_LEN;
5104     }
5105
5106     td->table_vacancy.vacancy_down = otv->vacancy_down;
5107     td->table_vacancy.vacancy_up = otv->vacancy_up;
5108     td->table_vacancy.vacancy = otv->vacancy;
5109     return 0;
5110 }
5111
5112 /* Decodes the next OpenFlow "table desc" message (of possibly several) from
5113  * 'msg' into an abstract form in '*td'.  Returns 0 if successful, EOF if the
5114  * last "table desc" in 'msg' was already decoded, otherwise an OFPERR_*
5115  * value. */
5116 int
5117 ofputil_decode_table_desc(struct ofpbuf *msg,
5118                           struct ofputil_table_desc *td,
5119                           enum ofp_version version)
5120 {
5121     memset(td, 0, sizeof *td);
5122
5123     if (!msg->header) {
5124         ofpraw_pull_assert(msg);
5125     }
5126
5127     if (!msg->size) {
5128         return EOF;
5129     }
5130
5131     struct ofp14_table_desc *otd = ofpbuf_try_pull(msg, sizeof *otd);
5132     if (!otd) {
5133         VLOG_WARN_RL(&bad_ofmsg_rl, "OFP14_TABLE_DESC reply has %"PRIu32" "
5134                      "leftover bytes at end", msg->size);
5135         return OFPERR_OFPBRC_BAD_LEN;
5136     }
5137
5138     td->table_id = otd->table_id;
5139     size_t length = ntohs(otd->length);
5140     if (length < sizeof *otd || length - sizeof *otd > msg->size) {
5141         VLOG_WARN_RL(&bad_ofmsg_rl, "OFP14_TABLE_DESC reply claims invalid "
5142                      "length %"PRIuSIZE, length);
5143         return OFPERR_OFPBRC_BAD_LEN;
5144     }
5145     length -= sizeof *otd;
5146
5147     td->eviction = ofputil_decode_table_eviction(otd->config, version);
5148     td->vacancy = ofputil_decode_table_vacancy(otd->config, version);
5149     td->eviction_flags = UINT32_MAX;
5150
5151     struct ofpbuf properties = ofpbuf_const_initializer(
5152         ofpbuf_pull(msg, length), length);
5153     while (properties.size > 0) {
5154         struct ofpbuf payload;
5155         enum ofperr error;
5156         uint64_t type;
5157
5158         error = ofpprop_pull(&properties, &payload, &type);
5159         if (error) {
5160             return error;
5161         }
5162
5163         switch (type) {
5164         case OFPTMPT14_EVICTION:
5165             error = ofpprop_parse_u32(&payload, &td->eviction_flags);
5166             break;
5167
5168         case OFPTMPT14_VACANCY:
5169             error = parse_table_desc_vacancy_property(&payload, td);
5170             break;
5171
5172         default:
5173             error = OFPPROP_UNKNOWN(true, "table_desc", type);
5174             break;
5175         }
5176
5177         if (error) {
5178             return error;
5179         }
5180     }
5181
5182     return 0;
5183 }
5184
5185 /* Encodes and returns a request to obtain description of tables of a switch.
5186  * The message is encoded for OpenFlow version 'ofp_version'. */
5187 struct ofpbuf *
5188 ofputil_encode_table_desc_request(enum ofp_version ofp_version)
5189 {
5190     struct ofpbuf *request = NULL;
5191
5192     if (ofp_version >= OFP14_VERSION) {
5193         request = ofpraw_alloc(OFPRAW_OFPST14_TABLE_DESC_REQUEST,
5194                                ofp_version, 0);
5195     } else {
5196         ovs_fatal(0, "dump-table-desc needs OpenFlow 1.4 or later "
5197                   "(\'-O OpenFlow14\')");
5198     }
5199
5200     return request;
5201 }
5202
5203 /* Function to append Table desc information in a reply list. */
5204 void
5205 ofputil_append_table_desc_reply(const struct ofputil_table_desc *td,
5206                                 struct ovs_list *replies,
5207                                 enum ofp_version version)
5208 {
5209     struct ofpbuf *reply = ofpbuf_from_list(list_back(replies));
5210     size_t start_otd;
5211     struct ofp14_table_desc *otd;
5212
5213     start_otd = reply->size;
5214     ofpbuf_put_zeros(reply, sizeof *otd);
5215     if (td->eviction_flags != UINT32_MAX) {
5216         ofpprop_put_u32(reply, OFPTMPT14_EVICTION, td->eviction_flags);
5217     }
5218     if (td->vacancy == OFPUTIL_TABLE_VACANCY_ON) {
5219         struct ofp14_table_mod_prop_vacancy *otv;
5220
5221         otv = ofpprop_put_zeros(reply, OFPTMPT14_VACANCY, sizeof *otv);
5222         otv->vacancy_down = td->table_vacancy.vacancy_down;
5223         otv->vacancy_up = td->table_vacancy.vacancy_up;
5224         otv->vacancy = td->table_vacancy.vacancy;
5225     }
5226
5227     otd = ofpbuf_at_assert(reply, start_otd, sizeof *otd);
5228     otd->length = htons(reply->size - start_otd);
5229     otd->table_id = td->table_id;
5230     otd->config = ofputil_encode_table_config(OFPUTIL_TABLE_MISS_DEFAULT,
5231                                               td->eviction, td->vacancy,
5232                                               version);
5233     ofpmp_postappend(replies, start_otd);
5234 }
5235
5236 /* This function parses Vacancy property, and decodes the
5237  * ofp14_table_mod_prop_vacancy in ofputil_table_mod.
5238  * Returns OFPERR_OFPBPC_BAD_VALUE error code when vacancy_down is
5239  * greater than vacancy_up and also when current vacancy has non-zero
5240  * value. Returns 0 on success. */
5241 static enum ofperr
5242 parse_table_mod_vacancy_property(struct ofpbuf *property,
5243                                  struct ofputil_table_mod *tm)
5244 {
5245     struct ofp14_table_mod_prop_vacancy *otv = property->data;
5246
5247     if (property->size != sizeof *otv) {
5248         return OFPERR_OFPBPC_BAD_LEN;
5249     }
5250     tm->table_vacancy.vacancy_down = otv->vacancy_down;
5251     tm->table_vacancy.vacancy_up = otv->vacancy_up;
5252     if (tm->table_vacancy.vacancy_down > tm->table_vacancy.vacancy_up) {
5253         OFPPROP_LOG(&bad_ofmsg_rl, false,
5254                     "Value of vacancy_down is greater than vacancy_up");
5255         return OFPERR_OFPBPC_BAD_VALUE;
5256     }
5257     if (tm->table_vacancy.vacancy_down > 100 ||
5258         tm->table_vacancy.vacancy_up > 100) {
5259         OFPPROP_LOG(&bad_ofmsg_rl, false, "Vacancy threshold percentage "
5260                     "should not be greater than 100");
5261         return OFPERR_OFPBPC_BAD_VALUE;
5262     }
5263     tm->table_vacancy.vacancy = otv->vacancy;
5264     if (tm->table_vacancy.vacancy) {
5265         OFPPROP_LOG(&bad_ofmsg_rl, false,
5266                     "Vacancy value should be zero for table-mod messages");
5267         return OFPERR_OFPBPC_BAD_VALUE;
5268     }
5269     return 0;
5270 }
5271
5272 /* Given 'config', taken from an OpenFlow 'version' message that specifies
5273  * table configuration (a table mod, table stats, or table features message),
5274  * returns the table vacancy configuration that it specifies.
5275  *
5276  * Only OpenFlow 1.4 and later specify table vacancy configuration this way,
5277  * so for other 'version' this function always returns
5278  * OFPUTIL_TABLE_VACANCY_DEFAULT. */
5279 static enum ofputil_table_vacancy
5280 ofputil_decode_table_vacancy(ovs_be32 config, enum ofp_version version)
5281 {
5282     return (version < OFP14_VERSION ? OFPUTIL_TABLE_VACANCY_DEFAULT
5283             : config & htonl(OFPTC14_VACANCY_EVENTS) ? OFPUTIL_TABLE_VACANCY_ON
5284             : OFPUTIL_TABLE_VACANCY_OFF);
5285 }
5286
5287 /* Given 'config', taken from an OpenFlow 'version' message that specifies
5288  * table configuration (a table mod, table stats, or table features message),
5289  * returns the table eviction configuration that it specifies.
5290  *
5291  * Only OpenFlow 1.4 and later specify table eviction configuration this way,
5292  * so for other 'version' values this function always returns
5293  * OFPUTIL_TABLE_EVICTION_DEFAULT. */
5294 static enum ofputil_table_eviction
5295 ofputil_decode_table_eviction(ovs_be32 config, enum ofp_version version)
5296 {
5297     return (version < OFP14_VERSION ? OFPUTIL_TABLE_EVICTION_DEFAULT
5298             : config & htonl(OFPTC14_EVICTION) ? OFPUTIL_TABLE_EVICTION_ON
5299             : OFPUTIL_TABLE_EVICTION_OFF);
5300 }
5301
5302 /* Returns a bitmap of OFPTC* values suitable for 'config' fields in various
5303  * OpenFlow messages of the given 'version', based on the provided 'miss' and
5304  * 'eviction' values. */
5305 static ovs_be32
5306 ofputil_encode_table_config(enum ofputil_table_miss miss,
5307                             enum ofputil_table_eviction eviction,
5308                             enum ofputil_table_vacancy vacancy,
5309                             enum ofp_version version)
5310 {
5311     uint32_t config = 0;
5312     /* See the section "OFPTC_* Table Configuration" in DESIGN.md for more
5313      * information on the crazy evolution of this field. */
5314     switch (version) {
5315     case OFP10_VERSION:
5316         /* OpenFlow 1.0 didn't have such a field, any value ought to do. */
5317         return htonl(0);
5318
5319     case OFP11_VERSION:
5320     case OFP12_VERSION:
5321         /* OpenFlow 1.1 and 1.2 define only OFPTC11_TABLE_MISS_*. */
5322         switch (miss) {
5323         case OFPUTIL_TABLE_MISS_DEFAULT:
5324             /* Really this shouldn't be used for encoding (the caller should
5325              * provide a specific value) but I can't imagine that defaulting to
5326              * the fall-through case here will hurt. */
5327         case OFPUTIL_TABLE_MISS_CONTROLLER:
5328         default:
5329             return htonl(OFPTC11_TABLE_MISS_CONTROLLER);
5330         case OFPUTIL_TABLE_MISS_CONTINUE:
5331             return htonl(OFPTC11_TABLE_MISS_CONTINUE);
5332         case OFPUTIL_TABLE_MISS_DROP:
5333             return htonl(OFPTC11_TABLE_MISS_DROP);
5334         }
5335         OVS_NOT_REACHED();
5336
5337     case OFP13_VERSION:
5338         /* OpenFlow 1.3 removed OFPTC11_TABLE_MISS_* and didn't define any new
5339          * flags, so this is correct. */
5340         return htonl(0);
5341
5342     case OFP14_VERSION:
5343     case OFP15_VERSION:
5344         /* OpenFlow 1.4 introduced OFPTC14_EVICTION and
5345          * OFPTC14_VACANCY_EVENTS. */
5346         if (eviction == OFPUTIL_TABLE_EVICTION_ON) {
5347             config |= OFPTC14_EVICTION;
5348         }
5349         if (vacancy == OFPUTIL_TABLE_VACANCY_ON) {
5350             config |= OFPTC14_VACANCY_EVENTS;
5351         }
5352         return htonl(config);
5353     }
5354
5355     OVS_NOT_REACHED();
5356 }
5357
5358 /* Given 'config', taken from an OpenFlow 'version' message that specifies
5359  * table configuration (a table mod, table stats, or table features message),
5360  * returns the table miss configuration that it specifies.
5361  *
5362  * Only OpenFlow 1.1 and 1.2 specify table miss configurations this way, so for
5363  * other 'version' values this function always returns
5364  * OFPUTIL_TABLE_MISS_DEFAULT. */
5365 static enum ofputil_table_miss
5366 ofputil_decode_table_miss(ovs_be32 config_, enum ofp_version version)
5367 {
5368     uint32_t config = ntohl(config_);
5369
5370     if (version == OFP11_VERSION || version == OFP12_VERSION) {
5371         switch (config & OFPTC11_TABLE_MISS_MASK) {
5372         case OFPTC11_TABLE_MISS_CONTROLLER:
5373             return OFPUTIL_TABLE_MISS_CONTROLLER;
5374
5375         case OFPTC11_TABLE_MISS_CONTINUE:
5376             return OFPUTIL_TABLE_MISS_CONTINUE;
5377
5378         case OFPTC11_TABLE_MISS_DROP:
5379             return OFPUTIL_TABLE_MISS_DROP;
5380
5381         default:
5382             VLOG_WARN_RL(&bad_ofmsg_rl, "bad table miss config %d", config);
5383             return OFPUTIL_TABLE_MISS_CONTROLLER;
5384         }
5385     } else {
5386         return OFPUTIL_TABLE_MISS_DEFAULT;
5387     }
5388 }
5389
5390 /* Decodes the OpenFlow "table mod" message in '*oh' into an abstract form in
5391  * '*pm'.  Returns 0 if successful, otherwise an OFPERR_* value. */
5392 enum ofperr
5393 ofputil_decode_table_mod(const struct ofp_header *oh,
5394                          struct ofputil_table_mod *pm)
5395 {
5396     memset(pm, 0, sizeof *pm);
5397     pm->miss = OFPUTIL_TABLE_MISS_DEFAULT;
5398     pm->eviction = OFPUTIL_TABLE_EVICTION_DEFAULT;
5399     pm->eviction_flags = UINT32_MAX;
5400     pm->vacancy = OFPUTIL_TABLE_VACANCY_DEFAULT;
5401
5402     struct ofpbuf b = ofpbuf_const_initializer(oh, ntohs(oh->length));
5403     enum ofpraw raw = ofpraw_pull_assert(&b);
5404     if (raw == OFPRAW_OFPT11_TABLE_MOD) {
5405         const struct ofp11_table_mod *otm = b.data;
5406
5407         pm->table_id = otm->table_id;
5408         pm->miss = ofputil_decode_table_miss(otm->config, oh->version);
5409     } else if (raw == OFPRAW_OFPT14_TABLE_MOD) {
5410         const struct ofp14_table_mod *otm = ofpbuf_pull(&b, sizeof *otm);
5411
5412         pm->table_id = otm->table_id;
5413         pm->miss = ofputil_decode_table_miss(otm->config, oh->version);
5414         pm->eviction = ofputil_decode_table_eviction(otm->config, oh->version);
5415         pm->vacancy = ofputil_decode_table_vacancy(otm->config, oh->version);
5416         while (b.size > 0) {
5417             struct ofpbuf property;
5418             enum ofperr error;
5419             uint64_t type;
5420
5421             error = ofpprop_pull(&b, &property, &type);
5422             if (error) {
5423                 return error;
5424             }
5425
5426             switch (type) {
5427             case OFPTMPT14_EVICTION:
5428                 error = ofpprop_parse_u32(&property, &pm->eviction);
5429                 break;
5430
5431             case OFPTMPT14_VACANCY:
5432                 error = parse_table_mod_vacancy_property(&property, pm);
5433                 break;
5434
5435             default:
5436                 error = OFPERR_OFPBRC_BAD_TYPE;
5437                 break;
5438             }
5439
5440             if (error) {
5441                 return error;
5442             }
5443         }
5444     } else {
5445         return OFPERR_OFPBRC_BAD_TYPE;
5446     }
5447
5448     return 0;
5449 }
5450
5451 /* Converts the abstract form of a "table mod" message in '*tm' into an
5452  * OpenFlow message suitable for 'protocol', and returns that encoded form in a
5453  * buffer owned by the caller. */
5454 struct ofpbuf *
5455 ofputil_encode_table_mod(const struct ofputil_table_mod *tm,
5456                         enum ofputil_protocol protocol)
5457 {
5458     enum ofp_version ofp_version = ofputil_protocol_to_ofp_version(protocol);
5459     struct ofpbuf *b;
5460
5461     switch (ofp_version) {
5462     case OFP10_VERSION: {
5463         ovs_fatal(0, "table mod needs OpenFlow 1.1 or later "
5464                      "(\'-O OpenFlow11\')");
5465         break;
5466     }
5467     case OFP11_VERSION:
5468     case OFP12_VERSION:
5469     case OFP13_VERSION: {
5470         struct ofp11_table_mod *otm;
5471
5472         b = ofpraw_alloc(OFPRAW_OFPT11_TABLE_MOD, ofp_version, 0);
5473         otm = ofpbuf_put_zeros(b, sizeof *otm);
5474         otm->table_id = tm->table_id;
5475         otm->config = ofputil_encode_table_config(tm->miss, tm->eviction,
5476                                                   tm->vacancy, ofp_version);
5477         break;
5478     }
5479     case OFP14_VERSION:
5480     case OFP15_VERSION: {
5481         struct ofp14_table_mod *otm;
5482
5483         b = ofpraw_alloc(OFPRAW_OFPT14_TABLE_MOD, ofp_version, 0);
5484         otm = ofpbuf_put_zeros(b, sizeof *otm);
5485         otm->table_id = tm->table_id;
5486         otm->config = ofputil_encode_table_config(tm->miss, tm->eviction,
5487                                                   tm->vacancy, ofp_version);
5488
5489         if (tm->eviction_flags != UINT32_MAX) {
5490             ofpprop_put_u32(b, OFPTMPT14_EVICTION, tm->eviction_flags);
5491         }
5492         if (tm->vacancy == OFPUTIL_TABLE_VACANCY_ON) {
5493             struct ofp14_table_mod_prop_vacancy *otv;
5494
5495             otv = ofpprop_put_zeros(b, OFPTMPT14_VACANCY, sizeof *otv);
5496             otv->vacancy_down = tm->table_vacancy.vacancy_down;
5497             otv->vacancy_up = tm->table_vacancy.vacancy_up;
5498         }
5499         break;
5500     }
5501     default:
5502         OVS_NOT_REACHED();
5503     }
5504
5505     return b;
5506 }
5507 \f
5508 /* ofputil_role_request */
5509
5510 /* Decodes the OpenFlow "role request" or "role reply" message in '*oh' into
5511  * an abstract form in '*rr'.  Returns 0 if successful, otherwise an
5512  * OFPERR_* value. */
5513 enum ofperr
5514 ofputil_decode_role_message(const struct ofp_header *oh,
5515                             struct ofputil_role_request *rr)
5516 {
5517     struct ofpbuf b = ofpbuf_const_initializer(oh, ntohs(oh->length));
5518     enum ofpraw raw = ofpraw_pull_assert(&b);
5519     if (raw == OFPRAW_OFPT12_ROLE_REQUEST ||
5520         raw == OFPRAW_OFPT12_ROLE_REPLY) {
5521         const struct ofp12_role_request *orr = b.msg;
5522
5523         if (orr->role != htonl(OFPCR12_ROLE_NOCHANGE) &&
5524             orr->role != htonl(OFPCR12_ROLE_EQUAL) &&
5525             orr->role != htonl(OFPCR12_ROLE_MASTER) &&
5526             orr->role != htonl(OFPCR12_ROLE_SLAVE)) {
5527             return OFPERR_OFPRRFC_BAD_ROLE;
5528         }
5529
5530         rr->role = ntohl(orr->role);
5531         if (raw == OFPRAW_OFPT12_ROLE_REQUEST
5532             ? orr->role == htonl(OFPCR12_ROLE_NOCHANGE)
5533             : orr->generation_id == OVS_BE64_MAX) {
5534             rr->have_generation_id = false;
5535             rr->generation_id = 0;
5536         } else {
5537             rr->have_generation_id = true;
5538             rr->generation_id = ntohll(orr->generation_id);
5539         }
5540     } else if (raw == OFPRAW_NXT_ROLE_REQUEST ||
5541                raw == OFPRAW_NXT_ROLE_REPLY) {
5542         const struct nx_role_request *nrr = b.msg;
5543
5544         BUILD_ASSERT(NX_ROLE_OTHER + 1 == OFPCR12_ROLE_EQUAL);
5545         BUILD_ASSERT(NX_ROLE_MASTER + 1 == OFPCR12_ROLE_MASTER);
5546         BUILD_ASSERT(NX_ROLE_SLAVE + 1 == OFPCR12_ROLE_SLAVE);
5547
5548         if (nrr->role != htonl(NX_ROLE_OTHER) &&
5549             nrr->role != htonl(NX_ROLE_MASTER) &&
5550             nrr->role != htonl(NX_ROLE_SLAVE)) {
5551             return OFPERR_OFPRRFC_BAD_ROLE;
5552         }
5553
5554         rr->role = ntohl(nrr->role) + 1;
5555         rr->have_generation_id = false;
5556         rr->generation_id = 0;
5557     } else {
5558         OVS_NOT_REACHED();
5559     }
5560
5561     return 0;
5562 }
5563
5564 /* Returns an encoded form of a role reply suitable for the "request" in a
5565  * buffer owned by the caller. */
5566 struct ofpbuf *
5567 ofputil_encode_role_reply(const struct ofp_header *request,
5568                           const struct ofputil_role_request *rr)
5569 {
5570     struct ofpbuf *buf;
5571     enum ofpraw raw;
5572
5573     raw = ofpraw_decode_assert(request);
5574     if (raw == OFPRAW_OFPT12_ROLE_REQUEST) {
5575         struct ofp12_role_request *orr;
5576
5577         buf = ofpraw_alloc_reply(OFPRAW_OFPT12_ROLE_REPLY, request, 0);
5578         orr = ofpbuf_put_zeros(buf, sizeof *orr);
5579
5580         orr->role = htonl(rr->role);
5581         orr->generation_id = htonll(rr->have_generation_id
5582                                     ? rr->generation_id
5583                                     : UINT64_MAX);
5584     } else if (raw == OFPRAW_NXT_ROLE_REQUEST) {
5585         struct nx_role_request *nrr;
5586
5587         BUILD_ASSERT(NX_ROLE_OTHER == OFPCR12_ROLE_EQUAL - 1);
5588         BUILD_ASSERT(NX_ROLE_MASTER == OFPCR12_ROLE_MASTER - 1);
5589         BUILD_ASSERT(NX_ROLE_SLAVE == OFPCR12_ROLE_SLAVE - 1);
5590
5591         buf = ofpraw_alloc_reply(OFPRAW_NXT_ROLE_REPLY, request, 0);
5592         nrr = ofpbuf_put_zeros(buf, sizeof *nrr);
5593         nrr->role = htonl(rr->role - 1);
5594     } else {
5595         OVS_NOT_REACHED();
5596     }
5597
5598     return buf;
5599 }
5600 \f
5601 /* Encodes "role status" message 'status' for sending in the given
5602  * 'protocol'.  Returns the role status message, if 'protocol' supports them,
5603  * otherwise a null pointer. */
5604 struct ofpbuf *
5605 ofputil_encode_role_status(const struct ofputil_role_status *status,
5606                            enum ofputil_protocol protocol)
5607 {
5608     enum ofp_version version;
5609
5610     version = ofputil_protocol_to_ofp_version(protocol);
5611     if (version >= OFP14_VERSION) {
5612         struct ofp14_role_status *rstatus;
5613         struct ofpbuf *buf;
5614
5615         buf = ofpraw_alloc_xid(OFPRAW_OFPT14_ROLE_STATUS, version, htonl(0),
5616                                0);
5617         rstatus = ofpbuf_put_zeros(buf, sizeof *rstatus);
5618         rstatus->role = htonl(status->role);
5619         rstatus->reason = status->reason;
5620         rstatus->generation_id = htonll(status->generation_id);
5621
5622         return buf;
5623     } else {
5624         return NULL;
5625     }
5626 }
5627
5628 enum ofperr
5629 ofputil_decode_role_status(const struct ofp_header *oh,
5630                            struct ofputil_role_status *rs)
5631 {
5632     struct ofpbuf b = ofpbuf_const_initializer(oh, ntohs(oh->length));
5633     enum ofpraw raw = ofpraw_pull_assert(&b);
5634     ovs_assert(raw == OFPRAW_OFPT14_ROLE_STATUS);
5635
5636     const struct ofp14_role_status *r = b.msg;
5637     if (r->role != htonl(OFPCR12_ROLE_NOCHANGE) &&
5638         r->role != htonl(OFPCR12_ROLE_EQUAL) &&
5639         r->role != htonl(OFPCR12_ROLE_MASTER) &&
5640         r->role != htonl(OFPCR12_ROLE_SLAVE)) {
5641         return OFPERR_OFPRRFC_BAD_ROLE;
5642     }
5643
5644     rs->role = ntohl(r->role);
5645     rs->generation_id = ntohll(r->generation_id);
5646     rs->reason = r->reason;
5647
5648     return 0;
5649 }
5650
5651 /* Encodes 'rf' according to 'protocol', and returns the encoded message.
5652  * 'protocol' must be for OpenFlow 1.4 or later. */
5653 struct ofpbuf *
5654 ofputil_encode_requestforward(const struct ofputil_requestforward *rf,
5655                               enum ofputil_protocol protocol)
5656 {
5657     enum ofp_version ofp_version = ofputil_protocol_to_ofp_version(protocol);
5658     struct ofpbuf *inner;
5659
5660     switch (rf->reason) {
5661     case OFPRFR_GROUP_MOD:
5662         inner = ofputil_encode_group_mod(ofp_version, rf->group_mod);
5663         break;
5664
5665     case OFPRFR_METER_MOD:
5666         inner = ofputil_encode_meter_mod(ofp_version, rf->meter_mod);
5667         break;
5668
5669     case OFPRFR_N_REASONS:
5670     default:
5671         OVS_NOT_REACHED();
5672     }
5673
5674     struct ofp_header *inner_oh = inner->data;
5675     inner_oh->xid = rf->xid;
5676     inner_oh->length = htons(inner->size);
5677
5678     struct ofpbuf *outer = ofpraw_alloc_xid(OFPRAW_OFPT14_REQUESTFORWARD,
5679                                             ofp_version, htonl(0),
5680                                             inner->size);
5681     ofpbuf_put(outer, inner->data, inner->size);
5682     ofpbuf_delete(inner);
5683
5684     return outer;
5685 }
5686
5687 /* Decodes OFPT_REQUESTFORWARD message 'outer'.  On success, puts the decoded
5688  * form into '*rf' and returns 0, and the caller is later responsible for
5689  * freeing the content of 'rf', with ofputil_destroy_requestforward(rf).  On
5690  * failure, returns an ofperr and '*rf' is indeterminate. */
5691 enum ofperr
5692 ofputil_decode_requestforward(const struct ofp_header *outer,
5693                               struct ofputil_requestforward *rf)
5694 {
5695     struct ofpbuf b = ofpbuf_const_initializer(outer, ntohs(outer->length));
5696
5697     /* Skip past outer message. */
5698     enum ofpraw outer_raw = ofpraw_pull_assert(&b);
5699     ovs_assert(outer_raw == OFPRAW_OFPT14_REQUESTFORWARD);
5700
5701     /* Validate inner message. */
5702     if (b.size < sizeof(struct ofp_header)) {
5703         return OFPERR_OFPBFC_MSG_BAD_LEN;
5704     }
5705     const struct ofp_header *inner = b.data;
5706     unsigned int inner_len = ntohs(inner->length);
5707     if (inner_len < sizeof(struct ofp_header) || inner_len > b.size) {
5708         return OFPERR_OFPBFC_MSG_BAD_LEN;
5709     }
5710     if (inner->version != outer->version) {
5711         return OFPERR_OFPBRC_BAD_VERSION;
5712     }
5713
5714     /* Parse inner message. */
5715     enum ofptype type;
5716     enum ofperr error = ofptype_decode(&type, inner);
5717     if (error) {
5718         return error;
5719     }
5720
5721     rf->xid = inner->xid;
5722     if (type == OFPTYPE_GROUP_MOD) {
5723         rf->reason = OFPRFR_GROUP_MOD;
5724         rf->group_mod = xmalloc(sizeof *rf->group_mod);
5725         error = ofputil_decode_group_mod(inner, rf->group_mod);
5726         if (error) {
5727             free(rf->group_mod);
5728             return error;
5729         }
5730     } else if (type == OFPTYPE_METER_MOD) {
5731         rf->reason = OFPRFR_METER_MOD;
5732         rf->meter_mod = xmalloc(sizeof *rf->meter_mod);
5733         ofpbuf_init(&rf->bands, 64);
5734         error = ofputil_decode_meter_mod(inner, rf->meter_mod, &rf->bands);
5735         if (error) {
5736             free(rf->meter_mod);
5737             ofpbuf_uninit(&rf->bands);
5738             return error;
5739         }
5740     } else {
5741         return OFPERR_OFPBFC_MSG_UNSUP;
5742     }
5743
5744     return 0;
5745 }
5746
5747 /* Frees the content of 'rf', which should have been initialized through a
5748  * successful call to ofputil_decode_requestforward(). */
5749 void
5750 ofputil_destroy_requestforward(struct ofputil_requestforward *rf)
5751 {
5752     if (!rf) {
5753         return;
5754     }
5755
5756     switch (rf->reason) {
5757     case OFPRFR_GROUP_MOD:
5758         ofputil_uninit_group_mod(rf->group_mod);
5759         free(rf->group_mod);
5760         break;
5761
5762     case OFPRFR_METER_MOD:
5763         ofpbuf_uninit(&rf->bands);
5764         free(rf->meter_mod);
5765         break;
5766
5767     case OFPRFR_N_REASONS:
5768         OVS_NOT_REACHED();
5769     }
5770 }
5771
5772 /* Table stats. */
5773
5774 /* OpenFlow 1.0 and 1.1 don't distinguish between a field that cannot be
5775  * matched and a field that must be wildcarded.  This function returns a bitmap
5776  * that contains both kinds of fields. */
5777 static struct mf_bitmap
5778 wild_or_nonmatchable_fields(const struct ofputil_table_features *features)
5779 {
5780     struct mf_bitmap wc = features->match;
5781     bitmap_not(wc.bm, MFF_N_IDS);
5782     bitmap_or(wc.bm, features->wildcard.bm, MFF_N_IDS);
5783     return wc;
5784 }
5785
5786 struct ofp10_wc_map {
5787     enum ofp10_flow_wildcards wc10;
5788     enum mf_field_id mf;
5789 };
5790
5791 static const struct ofp10_wc_map ofp10_wc_map[] = {
5792     { OFPFW10_IN_PORT,     MFF_IN_PORT },
5793     { OFPFW10_DL_VLAN,     MFF_VLAN_VID },
5794     { OFPFW10_DL_SRC,      MFF_ETH_SRC },
5795     { OFPFW10_DL_DST,      MFF_ETH_DST},
5796     { OFPFW10_DL_TYPE,     MFF_ETH_TYPE },
5797     { OFPFW10_NW_PROTO,    MFF_IP_PROTO },
5798     { OFPFW10_TP_SRC,      MFF_TCP_SRC },
5799     { OFPFW10_TP_DST,      MFF_TCP_DST },
5800     { OFPFW10_NW_SRC_MASK, MFF_IPV4_SRC },
5801     { OFPFW10_NW_DST_MASK, MFF_IPV4_DST },
5802     { OFPFW10_DL_VLAN_PCP, MFF_VLAN_PCP },
5803     { OFPFW10_NW_TOS,      MFF_IP_DSCP },
5804 };
5805
5806 static ovs_be32
5807 mf_bitmap_to_of10(const struct mf_bitmap *fields)
5808 {
5809     const struct ofp10_wc_map *p;
5810     uint32_t wc10 = 0;
5811
5812     for (p = ofp10_wc_map; p < &ofp10_wc_map[ARRAY_SIZE(ofp10_wc_map)]; p++) {
5813         if (bitmap_is_set(fields->bm, p->mf)) {
5814             wc10 |= p->wc10;
5815         }
5816     }
5817     return htonl(wc10);
5818 }
5819
5820 static struct mf_bitmap
5821 mf_bitmap_from_of10(ovs_be32 wc10_)
5822 {
5823     struct mf_bitmap fields = MF_BITMAP_INITIALIZER;
5824     const struct ofp10_wc_map *p;
5825     uint32_t wc10 = ntohl(wc10_);
5826
5827     for (p = ofp10_wc_map; p < &ofp10_wc_map[ARRAY_SIZE(ofp10_wc_map)]; p++) {
5828         if (wc10 & p->wc10) {
5829             bitmap_set1(fields.bm, p->mf);
5830         }
5831     }
5832     return fields;
5833 }
5834
5835 static void
5836 ofputil_put_ofp10_table_stats(const struct ofputil_table_stats *stats,
5837                               const struct ofputil_table_features *features,
5838                               struct ofpbuf *buf)
5839 {
5840     struct mf_bitmap wc = wild_or_nonmatchable_fields(features);
5841     struct ofp10_table_stats *out;
5842
5843     out = ofpbuf_put_zeros(buf, sizeof *out);
5844     out->table_id = features->table_id;
5845     ovs_strlcpy(out->name, features->name, sizeof out->name);
5846     out->wildcards = mf_bitmap_to_of10(&wc);
5847     out->max_entries = htonl(features->max_entries);
5848     out->active_count = htonl(stats->active_count);
5849     put_32aligned_be64(&out->lookup_count, htonll(stats->lookup_count));
5850     put_32aligned_be64(&out->matched_count, htonll(stats->matched_count));
5851 }
5852
5853 struct ofp11_wc_map {
5854     enum ofp11_flow_match_fields wc11;
5855     enum mf_field_id mf;
5856 };
5857
5858 static const struct ofp11_wc_map ofp11_wc_map[] = {
5859     { OFPFMF11_IN_PORT,     MFF_IN_PORT },
5860     { OFPFMF11_DL_VLAN,     MFF_VLAN_VID },
5861     { OFPFMF11_DL_VLAN_PCP, MFF_VLAN_PCP },
5862     { OFPFMF11_DL_TYPE,     MFF_ETH_TYPE },
5863     { OFPFMF11_NW_TOS,      MFF_IP_DSCP },
5864     { OFPFMF11_NW_PROTO,    MFF_IP_PROTO },
5865     { OFPFMF11_TP_SRC,      MFF_TCP_SRC },
5866     { OFPFMF11_TP_DST,      MFF_TCP_DST },
5867     { OFPFMF11_MPLS_LABEL,  MFF_MPLS_LABEL },
5868     { OFPFMF11_MPLS_TC,     MFF_MPLS_TC },
5869     /* I don't know what OFPFMF11_TYPE means. */
5870     { OFPFMF11_DL_SRC,      MFF_ETH_SRC },
5871     { OFPFMF11_DL_DST,      MFF_ETH_DST },
5872     { OFPFMF11_NW_SRC,      MFF_IPV4_SRC },
5873     { OFPFMF11_NW_DST,      MFF_IPV4_DST },
5874     { OFPFMF11_METADATA,    MFF_METADATA },
5875 };
5876
5877 static ovs_be32
5878 mf_bitmap_to_of11(const struct mf_bitmap *fields)
5879 {
5880     const struct ofp11_wc_map *p;
5881     uint32_t wc11 = 0;
5882
5883     for (p = ofp11_wc_map; p < &ofp11_wc_map[ARRAY_SIZE(ofp11_wc_map)]; p++) {
5884         if (bitmap_is_set(fields->bm, p->mf)) {
5885             wc11 |= p->wc11;
5886         }
5887     }
5888     return htonl(wc11);
5889 }
5890
5891 static struct mf_bitmap
5892 mf_bitmap_from_of11(ovs_be32 wc11_)
5893 {
5894     struct mf_bitmap fields = MF_BITMAP_INITIALIZER;
5895     const struct ofp11_wc_map *p;
5896     uint32_t wc11 = ntohl(wc11_);
5897
5898     for (p = ofp11_wc_map; p < &ofp11_wc_map[ARRAY_SIZE(ofp11_wc_map)]; p++) {
5899         if (wc11 & p->wc11) {
5900             bitmap_set1(fields.bm, p->mf);
5901         }
5902     }
5903     return fields;
5904 }
5905
5906 static void
5907 ofputil_put_ofp11_table_stats(const struct ofputil_table_stats *stats,
5908                               const struct ofputil_table_features *features,
5909                               struct ofpbuf *buf)
5910 {
5911     struct mf_bitmap wc = wild_or_nonmatchable_fields(features);
5912     struct ofp11_table_stats *out;
5913
5914     out = ofpbuf_put_zeros(buf, sizeof *out);
5915     out->table_id = features->table_id;
5916     ovs_strlcpy(out->name, features->name, sizeof out->name);
5917     out->wildcards = mf_bitmap_to_of11(&wc);
5918     out->match = mf_bitmap_to_of11(&features->match);
5919     out->instructions = ovsinst_bitmap_to_openflow(
5920         features->nonmiss.instructions, OFP11_VERSION);
5921     out->write_actions = ofpact_bitmap_to_openflow(
5922         features->nonmiss.write.ofpacts, OFP11_VERSION);
5923     out->apply_actions = ofpact_bitmap_to_openflow(
5924         features->nonmiss.apply.ofpacts, OFP11_VERSION);
5925     out->config = htonl(features->miss_config);
5926     out->max_entries = htonl(features->max_entries);
5927     out->active_count = htonl(stats->active_count);
5928     out->lookup_count = htonll(stats->lookup_count);
5929     out->matched_count = htonll(stats->matched_count);
5930 }
5931
5932 static void
5933 ofputil_put_ofp12_table_stats(const struct ofputil_table_stats *stats,
5934                               const struct ofputil_table_features *features,
5935                               struct ofpbuf *buf)
5936 {
5937     struct ofp12_table_stats *out;
5938
5939     out = ofpbuf_put_zeros(buf, sizeof *out);
5940     out->table_id = features->table_id;
5941     ovs_strlcpy(out->name, features->name, sizeof out->name);
5942     out->match = oxm_bitmap_from_mf_bitmap(&features->match, OFP12_VERSION);
5943     out->wildcards = oxm_bitmap_from_mf_bitmap(&features->wildcard,
5944                                              OFP12_VERSION);
5945     out->write_actions = ofpact_bitmap_to_openflow(
5946         features->nonmiss.write.ofpacts, OFP12_VERSION);
5947     out->apply_actions = ofpact_bitmap_to_openflow(
5948         features->nonmiss.apply.ofpacts, OFP12_VERSION);
5949     out->write_setfields = oxm_bitmap_from_mf_bitmap(
5950         &features->nonmiss.write.set_fields, OFP12_VERSION);
5951     out->apply_setfields = oxm_bitmap_from_mf_bitmap(
5952         &features->nonmiss.apply.set_fields, OFP12_VERSION);
5953     out->metadata_match = features->metadata_match;
5954     out->metadata_write = features->metadata_write;
5955     out->instructions = ovsinst_bitmap_to_openflow(
5956         features->nonmiss.instructions, OFP12_VERSION);
5957     out->config = ofputil_encode_table_config(features->miss_config,
5958                                               OFPUTIL_TABLE_EVICTION_DEFAULT,
5959                                               OFPUTIL_TABLE_VACANCY_DEFAULT,
5960                                               OFP12_VERSION);
5961     out->max_entries = htonl(features->max_entries);
5962     out->active_count = htonl(stats->active_count);
5963     out->lookup_count = htonll(stats->lookup_count);
5964     out->matched_count = htonll(stats->matched_count);
5965 }
5966
5967 static void
5968 ofputil_put_ofp13_table_stats(const struct ofputil_table_stats *stats,
5969                               struct ofpbuf *buf)
5970 {
5971     struct ofp13_table_stats *out;
5972
5973     out = ofpbuf_put_zeros(buf, sizeof *out);
5974     out->table_id = stats->table_id;
5975     out->active_count = htonl(stats->active_count);
5976     out->lookup_count = htonll(stats->lookup_count);
5977     out->matched_count = htonll(stats->matched_count);
5978 }
5979
5980 struct ofpbuf *
5981 ofputil_encode_table_stats_reply(const struct ofp_header *request)
5982 {
5983     return ofpraw_alloc_stats_reply(request, 0);
5984 }
5985
5986 void
5987 ofputil_append_table_stats_reply(struct ofpbuf *reply,
5988                                  const struct ofputil_table_stats *stats,
5989                                  const struct ofputil_table_features *features)
5990 {
5991     struct ofp_header *oh = reply->header;
5992
5993     ovs_assert(stats->table_id == features->table_id);
5994
5995     switch ((enum ofp_version) oh->version) {
5996     case OFP10_VERSION:
5997         ofputil_put_ofp10_table_stats(stats, features, reply);
5998         break;
5999
6000     case OFP11_VERSION:
6001         ofputil_put_ofp11_table_stats(stats, features, reply);
6002         break;
6003
6004     case OFP12_VERSION:
6005         ofputil_put_ofp12_table_stats(stats, features, reply);
6006         break;
6007
6008     case OFP13_VERSION:
6009     case OFP14_VERSION:
6010     case OFP15_VERSION:
6011         ofputil_put_ofp13_table_stats(stats, reply);
6012         break;
6013
6014     default:
6015         OVS_NOT_REACHED();
6016     }
6017 }
6018
6019 static int
6020 ofputil_decode_ofp10_table_stats(struct ofpbuf *msg,
6021                                  struct ofputil_table_stats *stats,
6022                                  struct ofputil_table_features *features)
6023 {
6024     struct ofp10_table_stats *ots;
6025
6026     ots = ofpbuf_try_pull(msg, sizeof *ots);
6027     if (!ots) {
6028         return OFPERR_OFPBRC_BAD_LEN;
6029     }
6030
6031     features->table_id = ots->table_id;
6032     ovs_strlcpy(features->name, ots->name, sizeof features->name);
6033     features->max_entries = ntohl(ots->max_entries);
6034     features->match = features->wildcard = mf_bitmap_from_of10(ots->wildcards);
6035
6036     stats->table_id = ots->table_id;
6037     stats->active_count = ntohl(ots->active_count);
6038     stats->lookup_count = ntohll(get_32aligned_be64(&ots->lookup_count));
6039     stats->matched_count = ntohll(get_32aligned_be64(&ots->matched_count));
6040
6041     return 0;
6042 }
6043
6044 static int
6045 ofputil_decode_ofp11_table_stats(struct ofpbuf *msg,
6046                                  struct ofputil_table_stats *stats,
6047                                  struct ofputil_table_features *features)
6048 {
6049     struct ofp11_table_stats *ots;
6050
6051     ots = ofpbuf_try_pull(msg, sizeof *ots);
6052     if (!ots) {
6053         return OFPERR_OFPBRC_BAD_LEN;
6054     }
6055
6056     features->table_id = ots->table_id;
6057     ovs_strlcpy(features->name, ots->name, sizeof features->name);
6058     features->max_entries = ntohl(ots->max_entries);
6059     features->nonmiss.instructions = ovsinst_bitmap_from_openflow(
6060         ots->instructions, OFP11_VERSION);
6061     features->nonmiss.write.ofpacts = ofpact_bitmap_from_openflow(
6062         ots->write_actions, OFP11_VERSION);
6063     features->nonmiss.apply.ofpacts = ofpact_bitmap_from_openflow(
6064         ots->write_actions, OFP11_VERSION);
6065     features->miss = features->nonmiss;
6066     features->miss_config = ofputil_decode_table_miss(ots->config,
6067                                                       OFP11_VERSION);
6068     features->match = mf_bitmap_from_of11(ots->match);
6069     features->wildcard = mf_bitmap_from_of11(ots->wildcards);
6070     bitmap_or(features->match.bm, features->wildcard.bm, MFF_N_IDS);
6071
6072     stats->table_id = ots->table_id;
6073     stats->active_count = ntohl(ots->active_count);
6074     stats->lookup_count = ntohll(ots->lookup_count);
6075     stats->matched_count = ntohll(ots->matched_count);
6076
6077     return 0;
6078 }
6079
6080 static int
6081 ofputil_decode_ofp12_table_stats(struct ofpbuf *msg,
6082                                  struct ofputil_table_stats *stats,
6083                                  struct ofputil_table_features *features)
6084 {
6085     struct ofp12_table_stats *ots;
6086
6087     ots = ofpbuf_try_pull(msg, sizeof *ots);
6088     if (!ots) {
6089         return OFPERR_OFPBRC_BAD_LEN;
6090     }
6091
6092     features->table_id = ots->table_id;
6093     ovs_strlcpy(features->name, ots->name, sizeof features->name);
6094     features->metadata_match = ots->metadata_match;
6095     features->metadata_write = ots->metadata_write;
6096     features->miss_config = ofputil_decode_table_miss(ots->config,
6097                                                       OFP12_VERSION);
6098     features->max_entries = ntohl(ots->max_entries);
6099
6100     features->nonmiss.instructions = ovsinst_bitmap_from_openflow(
6101         ots->instructions, OFP12_VERSION);
6102     features->nonmiss.write.ofpacts = ofpact_bitmap_from_openflow(
6103         ots->write_actions, OFP12_VERSION);
6104     features->nonmiss.apply.ofpacts = ofpact_bitmap_from_openflow(
6105         ots->apply_actions, OFP12_VERSION);
6106     features->nonmiss.write.set_fields = oxm_bitmap_to_mf_bitmap(
6107         ots->write_setfields, OFP12_VERSION);
6108     features->nonmiss.apply.set_fields = oxm_bitmap_to_mf_bitmap(
6109         ots->apply_setfields, OFP12_VERSION);
6110     features->miss = features->nonmiss;
6111
6112     features->match = oxm_bitmap_to_mf_bitmap(ots->match, OFP12_VERSION);
6113     features->wildcard = oxm_bitmap_to_mf_bitmap(ots->wildcards,
6114                                                  OFP12_VERSION);
6115     bitmap_or(features->match.bm, features->wildcard.bm, MFF_N_IDS);
6116
6117     stats->table_id = ots->table_id;
6118     stats->active_count = ntohl(ots->active_count);
6119     stats->lookup_count = ntohll(ots->lookup_count);
6120     stats->matched_count = ntohll(ots->matched_count);
6121
6122     return 0;
6123 }
6124
6125 static int
6126 ofputil_decode_ofp13_table_stats(struct ofpbuf *msg,
6127                                  struct ofputil_table_stats *stats,
6128                                  struct ofputil_table_features *features)
6129 {
6130     struct ofp13_table_stats *ots;
6131
6132     ots = ofpbuf_try_pull(msg, sizeof *ots);
6133     if (!ots) {
6134         return OFPERR_OFPBRC_BAD_LEN;
6135     }
6136
6137     features->table_id = ots->table_id;
6138
6139     stats->table_id = ots->table_id;
6140     stats->active_count = ntohl(ots->active_count);
6141     stats->lookup_count = ntohll(ots->lookup_count);
6142     stats->matched_count = ntohll(ots->matched_count);
6143
6144     return 0;
6145 }
6146
6147 int
6148 ofputil_decode_table_stats_reply(struct ofpbuf *msg,
6149                                  struct ofputil_table_stats *stats,
6150                                  struct ofputil_table_features *features)
6151 {
6152     const struct ofp_header *oh;
6153
6154     if (!msg->header) {
6155         ofpraw_pull_assert(msg);
6156     }
6157     oh = msg->header;
6158
6159     if (!msg->size) {
6160         return EOF;
6161     }
6162
6163     memset(stats, 0, sizeof *stats);
6164     memset(features, 0, sizeof *features);
6165     features->supports_eviction = -1;
6166     features->supports_vacancy_events = -1;
6167
6168     switch ((enum ofp_version) oh->version) {
6169     case OFP10_VERSION:
6170         return ofputil_decode_ofp10_table_stats(msg, stats, features);
6171
6172     case OFP11_VERSION:
6173         return ofputil_decode_ofp11_table_stats(msg, stats, features);
6174
6175     case OFP12_VERSION:
6176         return ofputil_decode_ofp12_table_stats(msg, stats, features);
6177
6178     case OFP13_VERSION:
6179     case OFP14_VERSION:
6180     case OFP15_VERSION:
6181         return ofputil_decode_ofp13_table_stats(msg, stats, features);
6182
6183     default:
6184         OVS_NOT_REACHED();
6185     }
6186 }
6187 \f
6188 /* ofputil_flow_monitor_request */
6189
6190 /* Converts an NXST_FLOW_MONITOR request in 'msg' into an abstract
6191  * ofputil_flow_monitor_request in 'rq'.
6192  *
6193  * Multiple NXST_FLOW_MONITOR requests can be packed into a single OpenFlow
6194  * message.  Calling this function multiple times for a single 'msg' iterates
6195  * through the requests.  The caller must initially leave 'msg''s layer
6196  * pointers null and not modify them between calls.
6197  *
6198  * Returns 0 if successful, EOF if no requests were left in this 'msg',
6199  * otherwise an OFPERR_* value. */
6200 int
6201 ofputil_decode_flow_monitor_request(struct ofputil_flow_monitor_request *rq,
6202                                     struct ofpbuf *msg)
6203 {
6204     struct nx_flow_monitor_request *nfmr;
6205     uint16_t flags;
6206
6207     if (!msg->header) {
6208         ofpraw_pull_assert(msg);
6209     }
6210
6211     if (!msg->size) {
6212         return EOF;
6213     }
6214
6215     nfmr = ofpbuf_try_pull(msg, sizeof *nfmr);
6216     if (!nfmr) {
6217         VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR request has %"PRIu32" "
6218                      "leftover bytes at end", msg->size);
6219         return OFPERR_OFPBRC_BAD_LEN;
6220     }
6221
6222     flags = ntohs(nfmr->flags);
6223     if (!(flags & (NXFMF_ADD | NXFMF_DELETE | NXFMF_MODIFY))
6224         || flags & ~(NXFMF_INITIAL | NXFMF_ADD | NXFMF_DELETE
6225                      | NXFMF_MODIFY | NXFMF_ACTIONS | NXFMF_OWN)) {
6226         VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR has bad flags %#"PRIx16,
6227                      flags);
6228         return OFPERR_OFPMOFC_BAD_FLAGS;
6229     }
6230
6231     if (!is_all_zeros(nfmr->zeros, sizeof nfmr->zeros)) {
6232         return OFPERR_NXBRC_MUST_BE_ZERO;
6233     }
6234
6235     rq->id = ntohl(nfmr->id);
6236     rq->flags = flags;
6237     rq->out_port = u16_to_ofp(ntohs(nfmr->out_port));
6238     rq->table_id = nfmr->table_id;
6239
6240     return nx_pull_match(msg, ntohs(nfmr->match_len), &rq->match, NULL, NULL);
6241 }
6242
6243 void
6244 ofputil_append_flow_monitor_request(
6245     const struct ofputil_flow_monitor_request *rq, struct ofpbuf *msg)
6246 {
6247     struct nx_flow_monitor_request *nfmr;
6248     size_t start_ofs;
6249     int match_len;
6250
6251     if (!msg->size) {
6252         ofpraw_put(OFPRAW_NXST_FLOW_MONITOR_REQUEST, OFP10_VERSION, msg);
6253     }
6254
6255     start_ofs = msg->size;
6256     ofpbuf_put_zeros(msg, sizeof *nfmr);
6257     match_len = nx_put_match(msg, &rq->match, htonll(0), htonll(0));
6258
6259     nfmr = ofpbuf_at_assert(msg, start_ofs, sizeof *nfmr);
6260     nfmr->id = htonl(rq->id);
6261     nfmr->flags = htons(rq->flags);
6262     nfmr->out_port = htons(ofp_to_u16(rq->out_port));
6263     nfmr->match_len = htons(match_len);
6264     nfmr->table_id = rq->table_id;
6265 }
6266
6267 /* Converts an NXST_FLOW_MONITOR reply (also known as a flow update) in 'msg'
6268  * into an abstract ofputil_flow_update in 'update'.  The caller must have
6269  * initialized update->match to point to space allocated for a match.
6270  *
6271  * Uses 'ofpacts' to store the abstract OFPACT_* version of the update's
6272  * actions (except for NXFME_ABBREV, which never includes actions).  The caller
6273  * must initialize 'ofpacts' and retains ownership of it.  'update->ofpacts'
6274  * will point into the 'ofpacts' buffer.
6275  *
6276  * Multiple flow updates can be packed into a single OpenFlow message.  Calling
6277  * this function multiple times for a single 'msg' iterates through the
6278  * updates.  The caller must initially leave 'msg''s layer pointers null and
6279  * not modify them between calls.
6280  *
6281  * Returns 0 if successful, EOF if no updates were left in this 'msg',
6282  * otherwise an OFPERR_* value. */
6283 int
6284 ofputil_decode_flow_update(struct ofputil_flow_update *update,
6285                            struct ofpbuf *msg, struct ofpbuf *ofpacts)
6286 {
6287     struct nx_flow_update_header *nfuh;
6288     unsigned int length;
6289     struct ofp_header *oh;
6290
6291     if (!msg->header) {
6292         ofpraw_pull_assert(msg);
6293     }
6294
6295     ofpbuf_clear(ofpacts);
6296     if (!msg->size) {
6297         return EOF;
6298     }
6299
6300     if (msg->size < sizeof(struct nx_flow_update_header)) {
6301         goto bad_len;
6302     }
6303
6304     oh = msg->header;
6305
6306     nfuh = msg->data;
6307     update->event = ntohs(nfuh->event);
6308     length = ntohs(nfuh->length);
6309     if (length > msg->size || length % 8) {
6310         goto bad_len;
6311     }
6312
6313     if (update->event == NXFME_ABBREV) {
6314         struct nx_flow_update_abbrev *nfua;
6315
6316         if (length != sizeof *nfua) {
6317             goto bad_len;
6318         }
6319
6320         nfua = ofpbuf_pull(msg, sizeof *nfua);
6321         update->xid = nfua->xid;
6322         return 0;
6323     } else if (update->event == NXFME_ADDED
6324                || update->event == NXFME_DELETED
6325                || update->event == NXFME_MODIFIED) {
6326         struct nx_flow_update_full *nfuf;
6327         unsigned int actions_len;
6328         unsigned int match_len;
6329         enum ofperr error;
6330
6331         if (length < sizeof *nfuf) {
6332             goto bad_len;
6333         }
6334
6335         nfuf = ofpbuf_pull(msg, sizeof *nfuf);
6336         match_len = ntohs(nfuf->match_len);
6337         if (sizeof *nfuf + match_len > length) {
6338             goto bad_len;
6339         }
6340
6341         update->reason = ntohs(nfuf->reason);
6342         update->idle_timeout = ntohs(nfuf->idle_timeout);
6343         update->hard_timeout = ntohs(nfuf->hard_timeout);
6344         update->table_id = nfuf->table_id;
6345         update->cookie = nfuf->cookie;
6346         update->priority = ntohs(nfuf->priority);
6347
6348         error = nx_pull_match(msg, match_len, update->match, NULL, NULL);
6349         if (error) {
6350             return error;
6351         }
6352
6353         actions_len = length - sizeof *nfuf - ROUND_UP(match_len, 8);
6354         error = ofpacts_pull_openflow_actions(msg, actions_len, oh->version,
6355                                               ofpacts);
6356         if (error) {
6357             return error;
6358         }
6359
6360         update->ofpacts = ofpacts->data;
6361         update->ofpacts_len = ofpacts->size;
6362         return 0;
6363     } else {
6364         VLOG_WARN_RL(&bad_ofmsg_rl,
6365                      "NXST_FLOW_MONITOR reply has bad event %"PRIu16,
6366                      ntohs(nfuh->event));
6367         return OFPERR_NXBRC_FM_BAD_EVENT;
6368     }
6369
6370 bad_len:
6371     VLOG_WARN_RL(&bad_ofmsg_rl, "NXST_FLOW_MONITOR reply has %"PRIu32" "
6372                  "leftover bytes at end", msg->size);
6373     return OFPERR_OFPBRC_BAD_LEN;
6374 }
6375
6376 uint32_t
6377 ofputil_decode_flow_monitor_cancel(const struct ofp_header *oh)
6378 {
6379     const struct nx_flow_monitor_cancel *cancel = ofpmsg_body(oh);
6380
6381     return ntohl(cancel->id);
6382 }
6383
6384 struct ofpbuf *
6385 ofputil_encode_flow_monitor_cancel(uint32_t id)
6386 {
6387     struct nx_flow_monitor_cancel *nfmc;
6388     struct ofpbuf *msg;
6389
6390     msg = ofpraw_alloc(OFPRAW_NXT_FLOW_MONITOR_CANCEL, OFP10_VERSION, 0);
6391     nfmc = ofpbuf_put_uninit(msg, sizeof *nfmc);
6392     nfmc->id = htonl(id);
6393     return msg;
6394 }
6395
6396 void
6397 ofputil_start_flow_update(struct ovs_list *replies)
6398 {
6399     struct ofpbuf *msg;
6400
6401     msg = ofpraw_alloc_xid(OFPRAW_NXST_FLOW_MONITOR_REPLY, OFP10_VERSION,
6402                            htonl(0), 1024);
6403
6404     list_init(replies);
6405     list_push_back(replies, &msg->list_node);
6406 }
6407
6408 void
6409 ofputil_append_flow_update(const struct ofputil_flow_update *update,
6410                            struct ovs_list *replies)
6411 {
6412     enum ofp_version version = ofpmp_version(replies);
6413     struct nx_flow_update_header *nfuh;
6414     struct ofpbuf *msg;
6415     size_t start_ofs;
6416
6417     msg = ofpbuf_from_list(list_back(replies));
6418     start_ofs = msg->size;
6419
6420     if (update->event == NXFME_ABBREV) {
6421         struct nx_flow_update_abbrev *nfua;
6422
6423         nfua = ofpbuf_put_zeros(msg, sizeof *nfua);
6424         nfua->xid = update->xid;
6425     } else {
6426         struct nx_flow_update_full *nfuf;
6427         int match_len;
6428
6429         ofpbuf_put_zeros(msg, sizeof *nfuf);
6430         match_len = nx_put_match(msg, update->match, htonll(0), htonll(0));
6431         ofpacts_put_openflow_actions(update->ofpacts, update->ofpacts_len, msg,
6432                                      version);
6433         nfuf = ofpbuf_at_assert(msg, start_ofs, sizeof *nfuf);
6434         nfuf->reason = htons(update->reason);
6435         nfuf->priority = htons(update->priority);
6436         nfuf->idle_timeout = htons(update->idle_timeout);
6437         nfuf->hard_timeout = htons(update->hard_timeout);
6438         nfuf->match_len = htons(match_len);
6439         nfuf->table_id = update->table_id;
6440         nfuf->cookie = update->cookie;
6441     }
6442
6443     nfuh = ofpbuf_at_assert(msg, start_ofs, sizeof *nfuh);
6444     nfuh->length = htons(msg->size - start_ofs);
6445     nfuh->event = htons(update->event);
6446
6447     ofpmp_postappend(replies, start_ofs);
6448 }
6449 \f
6450 struct ofpbuf *
6451 ofputil_encode_packet_out(const struct ofputil_packet_out *po,
6452                           enum ofputil_protocol protocol)
6453 {
6454     enum ofp_version ofp_version = ofputil_protocol_to_ofp_version(protocol);
6455     struct ofpbuf *msg;
6456     size_t size;
6457
6458     size = po->ofpacts_len;
6459     if (po->buffer_id == UINT32_MAX) {
6460         size += po->packet_len;
6461     }
6462
6463     switch (ofp_version) {
6464     case OFP10_VERSION: {
6465         struct ofp10_packet_out *opo;
6466         size_t actions_ofs;
6467
6468         msg = ofpraw_alloc(OFPRAW_OFPT10_PACKET_OUT, OFP10_VERSION, size);
6469         ofpbuf_put_zeros(msg, sizeof *opo);
6470         actions_ofs = msg->size;
6471         ofpacts_put_openflow_actions(po->ofpacts, po->ofpacts_len, msg,
6472                                      ofp_version);
6473
6474         opo = msg->msg;
6475         opo->buffer_id = htonl(po->buffer_id);
6476         opo->in_port = htons(ofp_to_u16(po->in_port));
6477         opo->actions_len = htons(msg->size - actions_ofs);
6478         break;
6479     }
6480
6481     case OFP11_VERSION:
6482     case OFP12_VERSION:
6483     case OFP13_VERSION:
6484     case OFP14_VERSION:
6485     case OFP15_VERSION: {
6486         struct ofp11_packet_out *opo;
6487         size_t len;
6488
6489         msg = ofpraw_alloc(OFPRAW_OFPT11_PACKET_OUT, ofp_version, size);
6490         ofpbuf_put_zeros(msg, sizeof *opo);
6491         len = ofpacts_put_openflow_actions(po->ofpacts, po->ofpacts_len, msg,
6492                                            ofp_version);
6493         opo = msg->msg;
6494         opo->buffer_id = htonl(po->buffer_id);
6495         opo->in_port = ofputil_port_to_ofp11(po->in_port);
6496         opo->actions_len = htons(len);
6497         break;
6498     }
6499
6500     default:
6501         OVS_NOT_REACHED();
6502     }
6503
6504     if (po->buffer_id == UINT32_MAX) {
6505         ofpbuf_put(msg, po->packet, po->packet_len);
6506     }
6507
6508     ofpmsg_update_length(msg);
6509
6510     return msg;
6511 }
6512 \f
6513 /* Creates and returns an OFPT_ECHO_REQUEST message with an empty payload. */
6514 struct ofpbuf *
6515 make_echo_request(enum ofp_version ofp_version)
6516 {
6517     return ofpraw_alloc_xid(OFPRAW_OFPT_ECHO_REQUEST, ofp_version,
6518                             htonl(0), 0);
6519 }
6520
6521 /* Creates and returns an OFPT_ECHO_REPLY message matching the
6522  * OFPT_ECHO_REQUEST message in 'rq'. */
6523 struct ofpbuf *
6524 make_echo_reply(const struct ofp_header *rq)
6525 {
6526     struct ofpbuf rq_buf = ofpbuf_const_initializer(rq, ntohs(rq->length));
6527     ofpraw_pull_assert(&rq_buf);
6528
6529     struct ofpbuf *reply = ofpraw_alloc_reply(OFPRAW_OFPT_ECHO_REPLY,
6530                                               rq, rq_buf.size);
6531     ofpbuf_put(reply, rq_buf.data, rq_buf.size);
6532     return reply;
6533 }
6534
6535 struct ofpbuf *
6536 ofputil_encode_barrier_request(enum ofp_version ofp_version)
6537 {
6538     enum ofpraw type;
6539
6540     switch (ofp_version) {
6541     case OFP15_VERSION:
6542     case OFP14_VERSION:
6543     case OFP13_VERSION:
6544     case OFP12_VERSION:
6545     case OFP11_VERSION:
6546         type = OFPRAW_OFPT11_BARRIER_REQUEST;
6547         break;
6548
6549     case OFP10_VERSION:
6550         type = OFPRAW_OFPT10_BARRIER_REQUEST;
6551         break;
6552
6553     default:
6554         OVS_NOT_REACHED();
6555     }
6556
6557     return ofpraw_alloc(type, ofp_version, 0);
6558 }
6559
6560 const char *
6561 ofputil_frag_handling_to_string(enum ofputil_frag_handling frag)
6562 {
6563     switch (frag) {
6564     case OFPUTIL_FRAG_NORMAL:   return "normal";
6565     case OFPUTIL_FRAG_DROP:     return "drop";
6566     case OFPUTIL_FRAG_REASM:    return "reassemble";
6567     case OFPUTIL_FRAG_NX_MATCH: return "nx-match";
6568     }
6569
6570     OVS_NOT_REACHED();
6571 }
6572
6573 bool
6574 ofputil_frag_handling_from_string(const char *s,
6575                                   enum ofputil_frag_handling *frag)
6576 {
6577     if (!strcasecmp(s, "normal")) {
6578         *frag = OFPUTIL_FRAG_NORMAL;
6579     } else if (!strcasecmp(s, "drop")) {
6580         *frag = OFPUTIL_FRAG_DROP;
6581     } else if (!strcasecmp(s, "reassemble")) {
6582         *frag = OFPUTIL_FRAG_REASM;
6583     } else if (!strcasecmp(s, "nx-match")) {
6584         *frag = OFPUTIL_FRAG_NX_MATCH;
6585     } else {
6586         return false;
6587     }
6588     return true;
6589 }
6590
6591 /* Converts the OpenFlow 1.1+ port number 'ofp11_port' into an OpenFlow 1.0
6592  * port number and stores the latter in '*ofp10_port', for the purpose of
6593  * decoding OpenFlow 1.1+ protocol messages.  Returns 0 if successful,
6594  * otherwise an OFPERR_* number.  On error, stores OFPP_NONE in '*ofp10_port'.
6595  *
6596  * See the definition of OFP11_MAX for an explanation of the mapping. */
6597 enum ofperr
6598 ofputil_port_from_ofp11(ovs_be32 ofp11_port, ofp_port_t *ofp10_port)
6599 {
6600     uint32_t ofp11_port_h = ntohl(ofp11_port);
6601
6602     if (ofp11_port_h < ofp_to_u16(OFPP_MAX)) {
6603         *ofp10_port = u16_to_ofp(ofp11_port_h);
6604         return 0;
6605     } else if (ofp11_port_h >= ofp11_to_u32(OFPP11_MAX)) {
6606         *ofp10_port = u16_to_ofp(ofp11_port_h - OFPP11_OFFSET);
6607         return 0;
6608     } else {
6609         *ofp10_port = OFPP_NONE;
6610         VLOG_WARN_RL(&bad_ofmsg_rl, "port %"PRIu32" is outside the supported "
6611                      "range 0 through %d or 0x%"PRIx32" through 0x%"PRIx32,
6612                      ofp11_port_h, ofp_to_u16(OFPP_MAX) - 1,
6613                      ofp11_to_u32(OFPP11_MAX), UINT32_MAX);
6614         return OFPERR_OFPBAC_BAD_OUT_PORT;
6615     }
6616 }
6617
6618 /* Returns the OpenFlow 1.1+ port number equivalent to the OpenFlow 1.0 port
6619  * number 'ofp10_port', for encoding OpenFlow 1.1+ protocol messages.
6620  *
6621  * See the definition of OFP11_MAX for an explanation of the mapping. */
6622 ovs_be32
6623 ofputil_port_to_ofp11(ofp_port_t ofp10_port)
6624 {
6625     return htonl(ofp_to_u16(ofp10_port) < ofp_to_u16(OFPP_MAX)
6626                  ? ofp_to_u16(ofp10_port)
6627                  : ofp_to_u16(ofp10_port) + OFPP11_OFFSET);
6628 }
6629
6630 #define OFPUTIL_NAMED_PORTS                     \
6631         OFPUTIL_NAMED_PORT(IN_PORT)             \
6632         OFPUTIL_NAMED_PORT(TABLE)               \
6633         OFPUTIL_NAMED_PORT(NORMAL)              \
6634         OFPUTIL_NAMED_PORT(FLOOD)               \
6635         OFPUTIL_NAMED_PORT(ALL)                 \
6636         OFPUTIL_NAMED_PORT(CONTROLLER)          \
6637         OFPUTIL_NAMED_PORT(LOCAL)               \
6638         OFPUTIL_NAMED_PORT(ANY)                 \
6639         OFPUTIL_NAMED_PORT(UNSET)
6640
6641 /* For backwards compatibility, so that "none" is recognized as OFPP_ANY */
6642 #define OFPUTIL_NAMED_PORTS_WITH_NONE           \
6643         OFPUTIL_NAMED_PORTS                     \
6644         OFPUTIL_NAMED_PORT(NONE)
6645
6646 /* Stores the port number represented by 's' into '*portp'.  's' may be an
6647  * integer or, for reserved ports, the standard OpenFlow name for the port
6648  * (e.g. "LOCAL").
6649  *
6650  * Returns true if successful, false if 's' is not a valid OpenFlow port number
6651  * or name.  The caller should issue an error message in this case, because
6652  * this function usually does not.  (This gives the caller an opportunity to
6653  * look up the port name another way, e.g. by contacting the switch and listing
6654  * the names of all its ports).
6655  *
6656  * This function accepts OpenFlow 1.0 port numbers.  It also accepts a subset
6657  * of OpenFlow 1.1+ port numbers, mapping those port numbers into the 16-bit
6658  * range as described in include/openflow/openflow-1.1.h. */
6659 bool
6660 ofputil_port_from_string(const char *s, ofp_port_t *portp)
6661 {
6662     unsigned int port32; /* int is at least 32 bits wide. */
6663
6664     if (*s == '-') {
6665         VLOG_WARN("Negative value %s is not a valid port number.", s);
6666         return false;
6667     }
6668     *portp = 0;
6669     if (str_to_uint(s, 10, &port32)) {
6670         if (port32 < ofp_to_u16(OFPP_MAX)) {
6671             /* Pass. */
6672         } else if (port32 < ofp_to_u16(OFPP_FIRST_RESV)) {
6673             VLOG_WARN("port %u is a reserved OF1.0 port number that will "
6674                       "be translated to %u when talking to an OF1.1 or "
6675                       "later controller", port32, port32 + OFPP11_OFFSET);
6676         } else if (port32 <= ofp_to_u16(OFPP_LAST_RESV)) {
6677             char name[OFP_MAX_PORT_NAME_LEN];
6678
6679             ofputil_port_to_string(u16_to_ofp(port32), name, sizeof name);
6680             VLOG_WARN_ONCE("referring to port %s as %"PRIu32" is deprecated "
6681                            "for compatibility with OpenFlow 1.1 and later",
6682                            name, port32);
6683         } else if (port32 < ofp11_to_u32(OFPP11_MAX)) {
6684             VLOG_WARN("port %u is outside the supported range 0 through "
6685                       "%"PRIx16" or 0x%x through 0x%"PRIx32, port32,
6686                       UINT16_MAX, ofp11_to_u32(OFPP11_MAX), UINT32_MAX);
6687             return false;
6688         } else {
6689             port32 -= OFPP11_OFFSET;
6690         }
6691
6692         *portp = u16_to_ofp(port32);
6693         return true;
6694     } else {
6695         struct pair {
6696             const char *name;
6697             ofp_port_t value;
6698         };
6699         static const struct pair pairs[] = {
6700 #define OFPUTIL_NAMED_PORT(NAME) {#NAME, OFPP_##NAME},
6701             OFPUTIL_NAMED_PORTS_WITH_NONE
6702 #undef OFPUTIL_NAMED_PORT
6703         };
6704         const struct pair *p;
6705
6706         for (p = pairs; p < &pairs[ARRAY_SIZE(pairs)]; p++) {
6707             if (!strcasecmp(s, p->name)) {
6708                 *portp = p->value;
6709                 return true;
6710             }
6711         }
6712         return false;
6713     }
6714 }
6715
6716 /* Appends to 's' a string representation of the OpenFlow port number 'port'.
6717  * Most ports' string representation is just the port number, but for special
6718  * ports, e.g. OFPP_LOCAL, it is the name, e.g. "LOCAL". */
6719 void
6720 ofputil_format_port(ofp_port_t port, struct ds *s)
6721 {
6722     char name[OFP_MAX_PORT_NAME_LEN];
6723
6724     ofputil_port_to_string(port, name, sizeof name);
6725     ds_put_cstr(s, name);
6726 }
6727
6728 /* Puts in the 'bufsize' byte in 'namebuf' a null-terminated string
6729  * representation of OpenFlow port number 'port'.  Most ports are represented
6730  * as just the port number, but special ports, e.g. OFPP_LOCAL, are represented
6731  * by name, e.g. "LOCAL". */
6732 void
6733 ofputil_port_to_string(ofp_port_t port,
6734                        char namebuf[OFP_MAX_PORT_NAME_LEN], size_t bufsize)
6735 {
6736     switch (port) {
6737 #define OFPUTIL_NAMED_PORT(NAME)                        \
6738         case OFPP_##NAME:                               \
6739             ovs_strlcpy(namebuf, #NAME, bufsize);       \
6740             break;
6741         OFPUTIL_NAMED_PORTS
6742 #undef OFPUTIL_NAMED_PORT
6743
6744     default:
6745         snprintf(namebuf, bufsize, "%"PRIu16, port);
6746         break;
6747     }
6748 }
6749
6750 /* Stores the group id represented by 's' into '*group_idp'.  's' may be an
6751  * integer or, for reserved group IDs, the standard OpenFlow name for the group
6752  * (either "ANY" or "ALL").
6753  *
6754  * Returns true if successful, false if 's' is not a valid OpenFlow group ID or
6755  * name. */
6756 bool
6757 ofputil_group_from_string(const char *s, uint32_t *group_idp)
6758 {
6759     if (!strcasecmp(s, "any")) {
6760         *group_idp = OFPG_ANY;
6761     } else if (!strcasecmp(s, "all")) {
6762         *group_idp = OFPG_ALL;
6763     } else if (!str_to_uint(s, 10, group_idp)) {
6764         VLOG_WARN("%s is not a valid group ID.  (Valid group IDs are "
6765                   "32-bit nonnegative integers or the keywords ANY or "
6766                   "ALL.)", s);
6767         return false;
6768     }
6769
6770     return true;
6771 }
6772
6773 /* Appends to 's' a string representation of the OpenFlow group ID 'group_id'.
6774  * Most groups' string representation is just the number, but for special
6775  * groups, e.g. OFPG_ALL, it is the name, e.g. "ALL". */
6776 void
6777 ofputil_format_group(uint32_t group_id, struct ds *s)
6778 {
6779     char name[MAX_GROUP_NAME_LEN];
6780
6781     ofputil_group_to_string(group_id, name, sizeof name);
6782     ds_put_cstr(s, name);
6783 }
6784
6785
6786 /* Puts in the 'bufsize' byte in 'namebuf' a null-terminated string
6787  * representation of OpenFlow group ID 'group_id'.  Most group are represented
6788  * as just their number, but special groups, e.g. OFPG_ALL, are represented
6789  * by name, e.g. "ALL". */
6790 void
6791 ofputil_group_to_string(uint32_t group_id,
6792                         char namebuf[MAX_GROUP_NAME_LEN + 1], size_t bufsize)
6793 {
6794     switch (group_id) {
6795     case OFPG_ALL:
6796         ovs_strlcpy(namebuf, "ALL", bufsize);
6797         break;
6798
6799     case OFPG_ANY:
6800         ovs_strlcpy(namebuf, "ANY", bufsize);
6801         break;
6802
6803     default:
6804         snprintf(namebuf, bufsize, "%"PRIu32, group_id);
6805         break;
6806     }
6807 }
6808
6809 /* Given a buffer 'b' that contains an array of OpenFlow ports of type
6810  * 'ofp_version', tries to pull the first element from the array.  If
6811  * successful, initializes '*pp' with an abstract representation of the
6812  * port and returns 0.  If no ports remain to be decoded, returns EOF.
6813  * On an error, returns a positive OFPERR_* value. */
6814 int
6815 ofputil_pull_phy_port(enum ofp_version ofp_version, struct ofpbuf *b,
6816                       struct ofputil_phy_port *pp)
6817 {
6818     memset(pp, 0, sizeof *pp);
6819
6820     switch (ofp_version) {
6821     case OFP10_VERSION: {
6822         const struct ofp10_phy_port *opp = ofpbuf_try_pull(b, sizeof *opp);
6823         return opp ? ofputil_decode_ofp10_phy_port(pp, opp) : EOF;
6824     }
6825     case OFP11_VERSION:
6826     case OFP12_VERSION:
6827     case OFP13_VERSION: {
6828         const struct ofp11_port *op = ofpbuf_try_pull(b, sizeof *op);
6829         return op ? ofputil_decode_ofp11_port(pp, op) : EOF;
6830     }
6831     case OFP14_VERSION:
6832     case OFP15_VERSION:
6833         return b->size ? ofputil_pull_ofp14_port(pp, b) : EOF;
6834     default:
6835         OVS_NOT_REACHED();
6836     }
6837 }
6838
6839 static void
6840 ofputil_normalize_match__(struct match *match, bool may_log)
6841 {
6842     enum {
6843         MAY_NW_ADDR     = 1 << 0, /* nw_src, nw_dst */
6844         MAY_TP_ADDR     = 1 << 1, /* tp_src, tp_dst */
6845         MAY_NW_PROTO    = 1 << 2, /* nw_proto */
6846         MAY_IPVx        = 1 << 3, /* tos, frag, ttl */
6847         MAY_ARP_SHA     = 1 << 4, /* arp_sha */
6848         MAY_ARP_THA     = 1 << 5, /* arp_tha */
6849         MAY_IPV6        = 1 << 6, /* ipv6_src, ipv6_dst, ipv6_label */
6850         MAY_ND_TARGET   = 1 << 7, /* nd_target */
6851         MAY_MPLS        = 1 << 8, /* mpls label and tc */
6852     } may_match;
6853
6854     struct flow_wildcards wc;
6855
6856     /* Figure out what fields may be matched. */
6857     if (match->flow.dl_type == htons(ETH_TYPE_IP)) {
6858         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_NW_ADDR;
6859         if (match->flow.nw_proto == IPPROTO_TCP ||
6860             match->flow.nw_proto == IPPROTO_UDP ||
6861             match->flow.nw_proto == IPPROTO_SCTP ||
6862             match->flow.nw_proto == IPPROTO_ICMP) {
6863             may_match |= MAY_TP_ADDR;
6864         }
6865     } else if (match->flow.dl_type == htons(ETH_TYPE_IPV6)) {
6866         may_match = MAY_NW_PROTO | MAY_IPVx | MAY_IPV6;
6867         if (match->flow.nw_proto == IPPROTO_TCP ||
6868             match->flow.nw_proto == IPPROTO_UDP ||
6869             match->flow.nw_proto == IPPROTO_SCTP) {
6870             may_match |= MAY_TP_ADDR;
6871         } else if (match->flow.nw_proto == IPPROTO_ICMPV6) {
6872             may_match |= MAY_TP_ADDR;
6873             if (match->flow.tp_src == htons(ND_NEIGHBOR_SOLICIT)) {
6874                 may_match |= MAY_ND_TARGET | MAY_ARP_SHA;
6875             } else if (match->flow.tp_src == htons(ND_NEIGHBOR_ADVERT)) {
6876                 may_match |= MAY_ND_TARGET | MAY_ARP_THA;
6877             }
6878         }
6879     } else if (match->flow.dl_type == htons(ETH_TYPE_ARP) ||
6880                match->flow.dl_type == htons(ETH_TYPE_RARP)) {
6881         may_match = MAY_NW_PROTO | MAY_NW_ADDR | MAY_ARP_SHA | MAY_ARP_THA;
6882     } else if (eth_type_mpls(match->flow.dl_type)) {
6883         may_match = MAY_MPLS;
6884     } else {
6885         may_match = 0;
6886     }
6887
6888     /* Clear the fields that may not be matched. */
6889     wc = match->wc;
6890     if (!(may_match & MAY_NW_ADDR)) {
6891         wc.masks.nw_src = wc.masks.nw_dst = htonl(0);
6892     }
6893     if (!(may_match & MAY_TP_ADDR)) {
6894         wc.masks.tp_src = wc.masks.tp_dst = htons(0);
6895     }
6896     if (!(may_match & MAY_NW_PROTO)) {
6897         wc.masks.nw_proto = 0;
6898     }
6899     if (!(may_match & MAY_IPVx)) {
6900         wc.masks.nw_tos = 0;
6901         wc.masks.nw_ttl = 0;
6902     }
6903     if (!(may_match & MAY_ARP_SHA)) {
6904         WC_UNMASK_FIELD(&wc, arp_sha);
6905     }
6906     if (!(may_match & MAY_ARP_THA)) {
6907         WC_UNMASK_FIELD(&wc, arp_tha);
6908     }
6909     if (!(may_match & MAY_IPV6)) {
6910         wc.masks.ipv6_src = wc.masks.ipv6_dst = in6addr_any;
6911         wc.masks.ipv6_label = htonl(0);
6912     }
6913     if (!(may_match & MAY_ND_TARGET)) {
6914         wc.masks.nd_target = in6addr_any;
6915     }
6916     if (!(may_match & MAY_MPLS)) {
6917         memset(wc.masks.mpls_lse, 0, sizeof wc.masks.mpls_lse);
6918     }
6919
6920     /* Log any changes. */
6921     if (!flow_wildcards_equal(&wc, &match->wc)) {
6922         bool log = may_log && !VLOG_DROP_INFO(&bad_ofmsg_rl);
6923         char *pre = log ? match_to_string(match, OFP_DEFAULT_PRIORITY) : NULL;
6924
6925         match->wc = wc;
6926         match_zero_wildcarded_fields(match);
6927
6928         if (log) {
6929             char *post = match_to_string(match, OFP_DEFAULT_PRIORITY);
6930             VLOG_INFO("normalization changed ofp_match, details:");
6931             VLOG_INFO(" pre: %s", pre);
6932             VLOG_INFO("post: %s", post);
6933             free(pre);
6934             free(post);
6935         }
6936     }
6937 }
6938
6939 /* "Normalizes" the wildcards in 'match'.  That means:
6940  *
6941  *    1. If the type of level N is known, then only the valid fields for that
6942  *       level may be specified.  For example, ARP does not have a TOS field,
6943  *       so nw_tos must be wildcarded if 'match' specifies an ARP flow.
6944  *       Similarly, IPv4 does not have any IPv6 addresses, so ipv6_src and
6945  *       ipv6_dst (and other fields) must be wildcarded if 'match' specifies an
6946  *       IPv4 flow.
6947  *
6948  *    2. If the type of level N is not known (or not understood by Open
6949  *       vSwitch), then no fields at all for that level may be specified.  For
6950  *       example, Open vSwitch does not understand SCTP, an L4 protocol, so the
6951  *       L4 fields tp_src and tp_dst must be wildcarded if 'match' specifies an
6952  *       SCTP flow.
6953  *
6954  * If this function changes 'match', it logs a rate-limited informational
6955  * message. */
6956 void
6957 ofputil_normalize_match(struct match *match)
6958 {
6959     ofputil_normalize_match__(match, true);
6960 }
6961
6962 /* Same as ofputil_normalize_match() without the logging.  Thus, this function
6963  * is suitable for a program's internal use, whereas ofputil_normalize_match()
6964  * sense for use on flows received from elsewhere (so that a bug in the program
6965  * that sent them can be reported and corrected). */
6966 void
6967 ofputil_normalize_match_quiet(struct match *match)
6968 {
6969     ofputil_normalize_match__(match, false);
6970 }
6971
6972 /* Parses a key or a key-value pair from '*stringp'.
6973  *
6974  * On success: Stores the key into '*keyp'.  Stores the value, if present, into
6975  * '*valuep', otherwise an empty string.  Advances '*stringp' past the end of
6976  * the key-value pair, preparing it for another call.  '*keyp' and '*valuep'
6977  * are substrings of '*stringp' created by replacing some of its bytes by null
6978  * terminators.  Returns true.
6979  *
6980  * If '*stringp' is just white space or commas, sets '*keyp' and '*valuep' to
6981  * NULL and returns false. */
6982 bool
6983 ofputil_parse_key_value(char **stringp, char **keyp, char **valuep)
6984 {
6985     char *pos, *key, *value;
6986     size_t key_len;
6987
6988     pos = *stringp;
6989     pos += strspn(pos, ", \t\r\n");
6990     if (*pos == '\0') {
6991         *keyp = *valuep = NULL;
6992         return false;
6993     }
6994
6995     key = pos;
6996     key_len = strcspn(pos, ":=(, \t\r\n");
6997     if (key[key_len] == ':' || key[key_len] == '=') {
6998         /* The value can be separated by a colon. */
6999         size_t value_len;
7000
7001         value = key + key_len + 1;
7002         value_len = strcspn(value, ", \t\r\n");
7003         pos = value + value_len + (value[value_len] != '\0');
7004         value[value_len] = '\0';
7005     } else if (key[key_len] == '(') {
7006         /* The value can be surrounded by balanced parentheses.  The outermost
7007          * set of parentheses is removed. */
7008         int level = 1;
7009         size_t value_len;
7010
7011         value = key + key_len + 1;
7012         for (value_len = 0; level > 0; value_len++) {
7013             switch (value[value_len]) {
7014             case '\0':
7015                 level = 0;
7016                 break;
7017
7018             case '(':
7019                 level++;
7020                 break;
7021
7022             case ')':
7023                 level--;
7024                 break;
7025             }
7026         }
7027         value[value_len - 1] = '\0';
7028         pos = value + value_len;
7029     } else {
7030         /* There might be no value at all. */
7031         value = key + key_len;  /* Will become the empty string below. */
7032         pos = key + key_len + (key[key_len] != '\0');
7033     }
7034     key[key_len] = '\0';
7035
7036     *stringp = pos;
7037     *keyp = key;
7038     *valuep = value;
7039     return true;
7040 }
7041
7042 /* Encode a dump ports request for 'port', the encoded message
7043  * will be for OpenFlow version 'ofp_version'. Returns message
7044  * as a struct ofpbuf. Returns encoded message on success, NULL on error */
7045 struct ofpbuf *
7046 ofputil_encode_dump_ports_request(enum ofp_version ofp_version, ofp_port_t port)
7047 {
7048     struct ofpbuf *request;
7049
7050     switch (ofp_version) {
7051     case OFP10_VERSION: {
7052         struct ofp10_port_stats_request *req;
7053         request = ofpraw_alloc(OFPRAW_OFPST10_PORT_REQUEST, ofp_version, 0);
7054         req = ofpbuf_put_zeros(request, sizeof *req);
7055         req->port_no = htons(ofp_to_u16(port));
7056         break;
7057     }
7058     case OFP11_VERSION:
7059     case OFP12_VERSION:
7060     case OFP13_VERSION:
7061     case OFP14_VERSION:
7062     case OFP15_VERSION: {
7063         struct ofp11_port_stats_request *req;
7064         request = ofpraw_alloc(OFPRAW_OFPST11_PORT_REQUEST, ofp_version, 0);
7065         req = ofpbuf_put_zeros(request, sizeof *req);
7066         req->port_no = ofputil_port_to_ofp11(port);
7067         break;
7068     }
7069     default:
7070         OVS_NOT_REACHED();
7071     }
7072
7073     return request;
7074 }
7075
7076 static void
7077 ofputil_port_stats_to_ofp10(const struct ofputil_port_stats *ops,
7078                             struct ofp10_port_stats *ps10)
7079 {
7080     ps10->port_no = htons(ofp_to_u16(ops->port_no));
7081     memset(ps10->pad, 0, sizeof ps10->pad);
7082     put_32aligned_be64(&ps10->rx_packets, htonll(ops->stats.rx_packets));
7083     put_32aligned_be64(&ps10->tx_packets, htonll(ops->stats.tx_packets));
7084     put_32aligned_be64(&ps10->rx_bytes, htonll(ops->stats.rx_bytes));
7085     put_32aligned_be64(&ps10->tx_bytes, htonll(ops->stats.tx_bytes));
7086     put_32aligned_be64(&ps10->rx_dropped, htonll(ops->stats.rx_dropped));
7087     put_32aligned_be64(&ps10->tx_dropped, htonll(ops->stats.tx_dropped));
7088     put_32aligned_be64(&ps10->rx_errors, htonll(ops->stats.rx_errors));
7089     put_32aligned_be64(&ps10->tx_errors, htonll(ops->stats.tx_errors));
7090     put_32aligned_be64(&ps10->rx_frame_err, htonll(ops->stats.rx_frame_errors));
7091     put_32aligned_be64(&ps10->rx_over_err, htonll(ops->stats.rx_over_errors));
7092     put_32aligned_be64(&ps10->rx_crc_err, htonll(ops->stats.rx_crc_errors));
7093     put_32aligned_be64(&ps10->collisions, htonll(ops->stats.collisions));
7094 }
7095
7096 static void
7097 ofputil_port_stats_to_ofp11(const struct ofputil_port_stats *ops,
7098                             struct ofp11_port_stats *ps11)
7099 {
7100     ps11->port_no = ofputil_port_to_ofp11(ops->port_no);
7101     memset(ps11->pad, 0, sizeof ps11->pad);
7102     ps11->rx_packets = htonll(ops->stats.rx_packets);
7103     ps11->tx_packets = htonll(ops->stats.tx_packets);
7104     ps11->rx_bytes = htonll(ops->stats.rx_bytes);
7105     ps11->tx_bytes = htonll(ops->stats.tx_bytes);
7106     ps11->rx_dropped = htonll(ops->stats.rx_dropped);
7107     ps11->tx_dropped = htonll(ops->stats.tx_dropped);
7108     ps11->rx_errors = htonll(ops->stats.rx_errors);
7109     ps11->tx_errors = htonll(ops->stats.tx_errors);
7110     ps11->rx_frame_err = htonll(ops->stats.rx_frame_errors);
7111     ps11->rx_over_err = htonll(ops->stats.rx_over_errors);
7112     ps11->rx_crc_err = htonll(ops->stats.rx_crc_errors);
7113     ps11->collisions = htonll(ops->stats.collisions);
7114 }
7115
7116 static void
7117 ofputil_port_stats_to_ofp13(const struct ofputil_port_stats *ops,
7118                             struct ofp13_port_stats *ps13)
7119 {
7120     ofputil_port_stats_to_ofp11(ops, &ps13->ps);
7121     ps13->duration_sec = htonl(ops->duration_sec);
7122     ps13->duration_nsec = htonl(ops->duration_nsec);
7123 }
7124
7125 static void
7126 ofputil_append_ofp14_port_stats(const struct ofputil_port_stats *ops,
7127                                 struct ovs_list *replies)
7128 {
7129     struct ofp14_port_stats_prop_ethernet *eth;
7130     struct ofp14_port_stats *ps14;
7131     struct ofpbuf *reply;
7132
7133     reply = ofpmp_reserve(replies, sizeof *ps14 + sizeof *eth);
7134
7135     ps14 = ofpbuf_put_uninit(reply, sizeof *ps14);
7136     ps14->length = htons(sizeof *ps14 + sizeof *eth);
7137     memset(ps14->pad, 0, sizeof ps14->pad);
7138     ps14->port_no = ofputil_port_to_ofp11(ops->port_no);
7139     ps14->duration_sec = htonl(ops->duration_sec);
7140     ps14->duration_nsec = htonl(ops->duration_nsec);
7141     ps14->rx_packets = htonll(ops->stats.rx_packets);
7142     ps14->tx_packets = htonll(ops->stats.tx_packets);
7143     ps14->rx_bytes = htonll(ops->stats.rx_bytes);
7144     ps14->tx_bytes = htonll(ops->stats.tx_bytes);
7145     ps14->rx_dropped = htonll(ops->stats.rx_dropped);
7146     ps14->tx_dropped = htonll(ops->stats.tx_dropped);
7147     ps14->rx_errors = htonll(ops->stats.rx_errors);
7148     ps14->tx_errors = htonll(ops->stats.tx_errors);
7149
7150     eth = ofpprop_put_zeros(reply, OFPPSPT14_ETHERNET, sizeof *eth);
7151     eth->rx_frame_err = htonll(ops->stats.rx_frame_errors);
7152     eth->rx_over_err = htonll(ops->stats.rx_over_errors);
7153     eth->rx_crc_err = htonll(ops->stats.rx_crc_errors);
7154     eth->collisions = htonll(ops->stats.collisions);
7155 }
7156
7157 /* Encode a ports stat for 'ops' and append it to 'replies'. */
7158 void
7159 ofputil_append_port_stat(struct ovs_list *replies,
7160                          const struct ofputil_port_stats *ops)
7161 {
7162     switch (ofpmp_version(replies)) {
7163     case OFP13_VERSION: {
7164         struct ofp13_port_stats *reply = ofpmp_append(replies, sizeof *reply);
7165         ofputil_port_stats_to_ofp13(ops, reply);
7166         break;
7167     }
7168     case OFP12_VERSION:
7169     case OFP11_VERSION: {
7170         struct ofp11_port_stats *reply = ofpmp_append(replies, sizeof *reply);
7171         ofputil_port_stats_to_ofp11(ops, reply);
7172         break;
7173     }
7174
7175     case OFP10_VERSION: {
7176         struct ofp10_port_stats *reply = ofpmp_append(replies, sizeof *reply);
7177         ofputil_port_stats_to_ofp10(ops, reply);
7178         break;
7179     }
7180
7181     case OFP14_VERSION:
7182     case OFP15_VERSION:
7183         ofputil_append_ofp14_port_stats(ops, replies);
7184         break;
7185
7186     default:
7187         OVS_NOT_REACHED();
7188     }
7189 }
7190
7191 static enum ofperr
7192 ofputil_port_stats_from_ofp10(struct ofputil_port_stats *ops,
7193                               const struct ofp10_port_stats *ps10)
7194 {
7195     memset(ops, 0, sizeof *ops);
7196
7197     ops->port_no = u16_to_ofp(ntohs(ps10->port_no));
7198     ops->stats.rx_packets = ntohll(get_32aligned_be64(&ps10->rx_packets));
7199     ops->stats.tx_packets = ntohll(get_32aligned_be64(&ps10->tx_packets));
7200     ops->stats.rx_bytes = ntohll(get_32aligned_be64(&ps10->rx_bytes));
7201     ops->stats.tx_bytes = ntohll(get_32aligned_be64(&ps10->tx_bytes));
7202     ops->stats.rx_dropped = ntohll(get_32aligned_be64(&ps10->rx_dropped));
7203     ops->stats.tx_dropped = ntohll(get_32aligned_be64(&ps10->tx_dropped));
7204     ops->stats.rx_errors = ntohll(get_32aligned_be64(&ps10->rx_errors));
7205     ops->stats.tx_errors = ntohll(get_32aligned_be64(&ps10->tx_errors));
7206     ops->stats.rx_frame_errors =
7207         ntohll(get_32aligned_be64(&ps10->rx_frame_err));
7208     ops->stats.rx_over_errors = ntohll(get_32aligned_be64(&ps10->rx_over_err));
7209     ops->stats.rx_crc_errors = ntohll(get_32aligned_be64(&ps10->rx_crc_err));
7210     ops->stats.collisions = ntohll(get_32aligned_be64(&ps10->collisions));
7211     ops->duration_sec = ops->duration_nsec = UINT32_MAX;
7212
7213     return 0;
7214 }
7215
7216 static enum ofperr
7217 ofputil_port_stats_from_ofp11(struct ofputil_port_stats *ops,
7218                               const struct ofp11_port_stats *ps11)
7219 {
7220     enum ofperr error;
7221
7222     memset(ops, 0, sizeof *ops);
7223     error = ofputil_port_from_ofp11(ps11->port_no, &ops->port_no);
7224     if (error) {
7225         return error;
7226     }
7227
7228     ops->stats.rx_packets = ntohll(ps11->rx_packets);
7229     ops->stats.tx_packets = ntohll(ps11->tx_packets);
7230     ops->stats.rx_bytes = ntohll(ps11->rx_bytes);
7231     ops->stats.tx_bytes = ntohll(ps11->tx_bytes);
7232     ops->stats.rx_dropped = ntohll(ps11->rx_dropped);
7233     ops->stats.tx_dropped = ntohll(ps11->tx_dropped);
7234     ops->stats.rx_errors = ntohll(ps11->rx_errors);
7235     ops->stats.tx_errors = ntohll(ps11->tx_errors);
7236     ops->stats.rx_frame_errors = ntohll(ps11->rx_frame_err);
7237     ops->stats.rx_over_errors = ntohll(ps11->rx_over_err);
7238     ops->stats.rx_crc_errors = ntohll(ps11->rx_crc_err);
7239     ops->stats.collisions = ntohll(ps11->collisions);
7240     ops->duration_sec = ops->duration_nsec = UINT32_MAX;
7241
7242     return 0;
7243 }
7244
7245 static enum ofperr
7246 ofputil_port_stats_from_ofp13(struct ofputil_port_stats *ops,
7247                               const struct ofp13_port_stats *ps13)
7248 {
7249     enum ofperr error = ofputil_port_stats_from_ofp11(ops, &ps13->ps);
7250     if (!error) {
7251         ops->duration_sec = ntohl(ps13->duration_sec);
7252         ops->duration_nsec = ntohl(ps13->duration_nsec);
7253     }
7254     return error;
7255 }
7256
7257 static enum ofperr
7258 parse_ofp14_port_stats_ethernet_property(const struct ofpbuf *payload,
7259                                          struct ofputil_port_stats *ops)
7260 {
7261     const struct ofp14_port_stats_prop_ethernet *eth = payload->data;
7262
7263     if (payload->size != sizeof *eth) {
7264         return OFPERR_OFPBPC_BAD_LEN;
7265     }
7266
7267     ops->stats.rx_frame_errors = ntohll(eth->rx_frame_err);
7268     ops->stats.rx_over_errors = ntohll(eth->rx_over_err);
7269     ops->stats.rx_crc_errors = ntohll(eth->rx_crc_err);
7270     ops->stats.collisions = ntohll(eth->collisions);
7271
7272     return 0;
7273 }
7274
7275 static enum ofperr
7276 ofputil_pull_ofp14_port_stats(struct ofputil_port_stats *ops,
7277                               struct ofpbuf *msg)
7278 {
7279     const struct ofp14_port_stats *ps14 = ofpbuf_try_pull(msg, sizeof *ps14);
7280     if (!ps14) {
7281         return OFPERR_OFPBRC_BAD_LEN;
7282     }
7283
7284     size_t len = ntohs(ps14->length);
7285     if (len < sizeof *ps14 || len - sizeof *ps14 > msg->size) {
7286         return OFPERR_OFPBRC_BAD_LEN;
7287     }
7288     len -= sizeof *ps14;
7289
7290     enum ofperr error = ofputil_port_from_ofp11(ps14->port_no, &ops->port_no);
7291     if (error) {
7292         return error;
7293     }
7294
7295     ops->duration_sec = ntohl(ps14->duration_sec);
7296     ops->duration_nsec = ntohl(ps14->duration_nsec);
7297     ops->stats.rx_packets = ntohll(ps14->rx_packets);
7298     ops->stats.tx_packets = ntohll(ps14->tx_packets);
7299     ops->stats.rx_bytes = ntohll(ps14->rx_bytes);
7300     ops->stats.tx_bytes = ntohll(ps14->tx_bytes);
7301     ops->stats.rx_dropped = ntohll(ps14->rx_dropped);
7302     ops->stats.tx_dropped = ntohll(ps14->tx_dropped);
7303     ops->stats.rx_errors = ntohll(ps14->rx_errors);
7304     ops->stats.tx_errors = ntohll(ps14->tx_errors);
7305     ops->stats.rx_frame_errors = UINT64_MAX;
7306     ops->stats.rx_over_errors = UINT64_MAX;
7307     ops->stats.rx_crc_errors = UINT64_MAX;
7308     ops->stats.collisions = UINT64_MAX;
7309
7310     struct ofpbuf properties = ofpbuf_const_initializer(ofpbuf_pull(msg, len),
7311                                                         len);
7312     while (properties.size > 0) {
7313         struct ofpbuf payload;
7314         enum ofperr error;
7315         uint64_t type;
7316
7317         error = ofpprop_pull(&properties, &payload, &type);
7318         if (error) {
7319             return error;
7320         }
7321
7322         switch (type) {
7323         case OFPPSPT14_ETHERNET:
7324             error = parse_ofp14_port_stats_ethernet_property(&payload, ops);
7325             break;
7326
7327         default:
7328             error = OFPPROP_UNKNOWN(true, "port stats", type);
7329             break;
7330         }
7331
7332         if (error) {
7333             return error;
7334         }
7335     }
7336
7337     return 0;
7338 }
7339
7340 /* Returns the number of port stats elements in OFPTYPE_PORT_STATS_REPLY
7341  * message 'oh'. */
7342 size_t
7343 ofputil_count_port_stats(const struct ofp_header *oh)
7344 {
7345     struct ofpbuf b = ofpbuf_const_initializer(oh, ntohs(oh->length));
7346     ofpraw_pull_assert(&b);
7347
7348     for (size_t n = 0; ; n++) {
7349         struct ofputil_port_stats ps;
7350         if (ofputil_decode_port_stats(&ps, &b)) {
7351             return n;
7352         }
7353     }
7354 }
7355
7356 /* Converts an OFPST_PORT_STATS reply in 'msg' into an abstract
7357  * ofputil_port_stats in 'ps'.
7358  *
7359  * Multiple OFPST_PORT_STATS replies can be packed into a single OpenFlow
7360  * message.  Calling this function multiple times for a single 'msg' iterates
7361  * through the replies.  The caller must initially leave 'msg''s layer pointers
7362  * null and not modify them between calls.
7363  *
7364  * Returns 0 if successful, EOF if no replies were left in this 'msg',
7365  * otherwise a positive errno value. */
7366 int
7367 ofputil_decode_port_stats(struct ofputil_port_stats *ps, struct ofpbuf *msg)
7368 {
7369     enum ofperr error;
7370     enum ofpraw raw;
7371
7372     error = (msg->header ? ofpraw_decode(&raw, msg->header)
7373              : ofpraw_pull(&raw, msg));
7374     if (error) {
7375         return error;
7376     }
7377
7378     if (!msg->size) {
7379         return EOF;
7380     } else if (raw == OFPRAW_OFPST14_PORT_REPLY) {
7381         return ofputil_pull_ofp14_port_stats(ps, msg);
7382     } else if (raw == OFPRAW_OFPST13_PORT_REPLY) {
7383         const struct ofp13_port_stats *ps13;
7384
7385         ps13 = ofpbuf_try_pull(msg, sizeof *ps13);
7386         if (!ps13) {
7387             goto bad_len;
7388         }
7389         return ofputil_port_stats_from_ofp13(ps, ps13);
7390     } else if (raw == OFPRAW_OFPST11_PORT_REPLY) {
7391         const struct ofp11_port_stats *ps11;
7392
7393         ps11 = ofpbuf_try_pull(msg, sizeof *ps11);
7394         if (!ps11) {
7395             goto bad_len;
7396         }
7397         return ofputil_port_stats_from_ofp11(ps, ps11);
7398     } else if (raw == OFPRAW_OFPST10_PORT_REPLY) {
7399         const struct ofp10_port_stats *ps10;
7400
7401         ps10 = ofpbuf_try_pull(msg, sizeof *ps10);
7402         if (!ps10) {
7403             goto bad_len;
7404         }
7405         return ofputil_port_stats_from_ofp10(ps, ps10);
7406     } else {
7407         OVS_NOT_REACHED();
7408     }
7409
7410  bad_len:
7411     VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_PORT reply has %"PRIu32" leftover "
7412                  "bytes at end", msg->size);
7413     return OFPERR_OFPBRC_BAD_LEN;
7414 }
7415
7416 /* Parse a port status request message into a 16 bit OpenFlow 1.0
7417  * port number and stores the latter in '*ofp10_port'.
7418  * Returns 0 if successful, otherwise an OFPERR_* number. */
7419 enum ofperr
7420 ofputil_decode_port_stats_request(const struct ofp_header *request,
7421                                   ofp_port_t *ofp10_port)
7422 {
7423     switch ((enum ofp_version)request->version) {
7424     case OFP15_VERSION:
7425     case OFP14_VERSION:
7426     case OFP13_VERSION:
7427     case OFP12_VERSION:
7428     case OFP11_VERSION: {
7429         const struct ofp11_port_stats_request *psr11 = ofpmsg_body(request);
7430         return ofputil_port_from_ofp11(psr11->port_no, ofp10_port);
7431     }
7432
7433     case OFP10_VERSION: {
7434         const struct ofp10_port_stats_request *psr10 = ofpmsg_body(request);
7435         *ofp10_port = u16_to_ofp(ntohs(psr10->port_no));
7436         return 0;
7437     }
7438
7439     default:
7440         OVS_NOT_REACHED();
7441     }
7442 }
7443
7444 /* Frees all of the "struct ofputil_bucket"s in the 'buckets' list. */
7445 void
7446 ofputil_bucket_list_destroy(struct ovs_list *buckets)
7447 {
7448     struct ofputil_bucket *bucket;
7449
7450     LIST_FOR_EACH_POP (bucket, list_node, buckets) {
7451         free(bucket->ofpacts);
7452         free(bucket);
7453     }
7454 }
7455
7456 /* Clones 'bucket' and its ofpacts data */
7457 static struct ofputil_bucket *
7458 ofputil_bucket_clone_data(const struct ofputil_bucket *bucket)
7459 {
7460     struct ofputil_bucket *new;
7461
7462     new = xmemdup(bucket, sizeof *bucket);
7463     new->ofpacts = xmemdup(bucket->ofpacts, bucket->ofpacts_len);
7464
7465     return new;
7466 }
7467
7468 /* Clones each of the buckets in the list 'src' appending them
7469  * in turn to 'dest' which should be an initialised list.
7470  * An exception is that if the pointer value of a bucket in 'src'
7471  * matches 'skip' then it is not cloned or appended to 'dest'.
7472  * This allows all of 'src' or 'all of 'src' except 'skip' to
7473  * be cloned and appended to 'dest'. */
7474 void
7475 ofputil_bucket_clone_list(struct ovs_list *dest, const struct ovs_list *src,
7476                           const struct ofputil_bucket *skip)
7477 {
7478     struct ofputil_bucket *bucket;
7479
7480     LIST_FOR_EACH (bucket, list_node, src) {
7481         struct ofputil_bucket *new_bucket;
7482
7483         if (bucket == skip) {
7484             continue;
7485         }
7486
7487         new_bucket = ofputil_bucket_clone_data(bucket);
7488         list_push_back(dest, &new_bucket->list_node);
7489     }
7490 }
7491
7492 /* Find a bucket in the list 'buckets' whose bucket id is 'bucket_id'
7493  * Returns the first bucket found or NULL if no buckets are found. */
7494 struct ofputil_bucket *
7495 ofputil_bucket_find(const struct ovs_list *buckets, uint32_t bucket_id)
7496 {
7497     struct ofputil_bucket *bucket;
7498
7499     if (bucket_id > OFPG15_BUCKET_MAX) {
7500         return NULL;
7501     }
7502
7503     LIST_FOR_EACH (bucket, list_node, buckets) {
7504         if (bucket->bucket_id == bucket_id) {
7505             return bucket;
7506         }
7507     }
7508
7509     return NULL;
7510 }
7511
7512 /* Returns true if more than one bucket in the list 'buckets'
7513  * have the same bucket id. Returns false otherwise. */
7514 bool
7515 ofputil_bucket_check_duplicate_id(const struct ovs_list *buckets)
7516 {
7517     struct ofputil_bucket *i, *j;
7518
7519     LIST_FOR_EACH (i, list_node, buckets) {
7520         LIST_FOR_EACH_REVERSE (j, list_node, buckets) {
7521             if (i == j) {
7522                 break;
7523             }
7524             if (i->bucket_id == j->bucket_id) {
7525                 return true;
7526             }
7527         }
7528     }
7529
7530     return false;
7531 }
7532
7533 /* Returns the bucket at the front of the list 'buckets'.
7534  * Undefined if 'buckets is empty. */
7535 struct ofputil_bucket *
7536 ofputil_bucket_list_front(const struct ovs_list *buckets)
7537 {
7538     static struct ofputil_bucket *bucket;
7539
7540     ASSIGN_CONTAINER(bucket, list_front(buckets), list_node);
7541
7542     return bucket;
7543 }
7544
7545 /* Returns the bucket at the back of the list 'buckets'.
7546  * Undefined if 'buckets is empty. */
7547 struct ofputil_bucket *
7548 ofputil_bucket_list_back(const struct ovs_list *buckets)
7549 {
7550     static struct ofputil_bucket *bucket;
7551
7552     ASSIGN_CONTAINER(bucket, list_back(buckets), list_node);
7553
7554     return bucket;
7555 }
7556
7557 /* Returns an OpenFlow group stats request for OpenFlow version 'ofp_version',
7558  * that requests stats for group 'group_id'.  (Use OFPG_ALL to request stats
7559  * for all groups.)
7560  *
7561  * Group statistics include packet and byte counts for each group. */
7562 struct ofpbuf *
7563 ofputil_encode_group_stats_request(enum ofp_version ofp_version,
7564                                    uint32_t group_id)
7565 {
7566     struct ofpbuf *request;
7567
7568     switch (ofp_version) {
7569     case OFP10_VERSION:
7570         ovs_fatal(0, "dump-group-stats needs OpenFlow 1.1 or later "
7571                      "(\'-O OpenFlow11\')");
7572     case OFP11_VERSION:
7573     case OFP12_VERSION:
7574     case OFP13_VERSION:
7575     case OFP14_VERSION:
7576     case OFP15_VERSION: {
7577         struct ofp11_group_stats_request *req;
7578         request = ofpraw_alloc(OFPRAW_OFPST11_GROUP_REQUEST, ofp_version, 0);
7579         req = ofpbuf_put_zeros(request, sizeof *req);
7580         req->group_id = htonl(group_id);
7581         break;
7582     }
7583     default:
7584         OVS_NOT_REACHED();
7585     }
7586
7587     return request;
7588 }
7589
7590 void
7591 ofputil_uninit_group_desc(struct ofputil_group_desc *gd)
7592 {
7593     ofputil_bucket_list_destroy(&gd->buckets);
7594     free(&gd->props.fields);
7595 }
7596
7597 /* Decodes the OpenFlow group description request in 'oh', returning the group
7598  * whose description is requested, or OFPG_ALL if stats for all groups was
7599  * requested. */
7600 uint32_t
7601 ofputil_decode_group_desc_request(const struct ofp_header *oh)
7602 {
7603     struct ofpbuf request = ofpbuf_const_initializer(oh, ntohs(oh->length));
7604     enum ofpraw raw = ofpraw_pull_assert(&request);
7605     if (raw == OFPRAW_OFPST11_GROUP_DESC_REQUEST) {
7606         return OFPG_ALL;
7607     } else if (raw == OFPRAW_OFPST15_GROUP_DESC_REQUEST) {
7608         ovs_be32 *group_id = ofpbuf_pull(&request, sizeof *group_id);
7609         return ntohl(*group_id);
7610     } else {
7611         OVS_NOT_REACHED();
7612     }
7613 }
7614
7615 /* Returns an OpenFlow group description request for OpenFlow version
7616  * 'ofp_version', that requests stats for group 'group_id'.  Use OFPG_ALL to
7617  * request stats for all groups (OpenFlow 1.4 and earlier always request all
7618  * groups).
7619  *
7620  * Group descriptions include the bucket and action configuration for each
7621  * group. */
7622 struct ofpbuf *
7623 ofputil_encode_group_desc_request(enum ofp_version ofp_version,
7624                                   uint32_t group_id)
7625 {
7626     struct ofpbuf *request;
7627
7628     switch (ofp_version) {
7629     case OFP10_VERSION:
7630         ovs_fatal(0, "dump-groups needs OpenFlow 1.1 or later "
7631                      "(\'-O OpenFlow11\')");
7632     case OFP11_VERSION:
7633     case OFP12_VERSION:
7634     case OFP13_VERSION:
7635     case OFP14_VERSION:
7636         request = ofpraw_alloc(OFPRAW_OFPST11_GROUP_DESC_REQUEST,
7637                                ofp_version, 0);
7638         break;
7639     case OFP15_VERSION:{
7640         struct ofp15_group_desc_request *req;
7641         request = ofpraw_alloc(OFPRAW_OFPST15_GROUP_DESC_REQUEST,
7642                                ofp_version, 0);
7643         req = ofpbuf_put_zeros(request, sizeof *req);
7644         req->group_id = htonl(group_id);
7645         break;
7646     }
7647     default:
7648         OVS_NOT_REACHED();
7649     }
7650
7651     return request;
7652 }
7653
7654 static void
7655 ofputil_group_bucket_counters_to_ofp11(const struct ofputil_group_stats *gs,
7656                                     struct ofp11_bucket_counter bucket_cnts[])
7657 {
7658     int i;
7659
7660     for (i = 0; i < gs->n_buckets; i++) {
7661        bucket_cnts[i].packet_count = htonll(gs->bucket_stats[i].packet_count);
7662        bucket_cnts[i].byte_count = htonll(gs->bucket_stats[i].byte_count);
7663     }
7664 }
7665
7666 static void
7667 ofputil_group_stats_to_ofp11(const struct ofputil_group_stats *gs,
7668                              struct ofp11_group_stats *gs11, size_t length,
7669                              struct ofp11_bucket_counter bucket_cnts[])
7670 {
7671     memset(gs11, 0, sizeof *gs11);
7672     gs11->length = htons(length);
7673     gs11->group_id = htonl(gs->group_id);
7674     gs11->ref_count = htonl(gs->ref_count);
7675     gs11->packet_count = htonll(gs->packet_count);
7676     gs11->byte_count = htonll(gs->byte_count);
7677     ofputil_group_bucket_counters_to_ofp11(gs, bucket_cnts);
7678 }
7679
7680 static void
7681 ofputil_group_stats_to_ofp13(const struct ofputil_group_stats *gs,
7682                              struct ofp13_group_stats *gs13, size_t length,
7683                              struct ofp11_bucket_counter bucket_cnts[])
7684 {
7685     ofputil_group_stats_to_ofp11(gs, &gs13->gs, length, bucket_cnts);
7686     gs13->duration_sec = htonl(gs->duration_sec);
7687     gs13->duration_nsec = htonl(gs->duration_nsec);
7688
7689 }
7690
7691 /* Encodes 'gs' properly for the format of the list of group statistics
7692  * replies already begun in 'replies' and appends it to the list.  'replies'
7693  * must have originally been initialized with ofpmp_init(). */
7694 void
7695 ofputil_append_group_stats(struct ovs_list *replies,
7696                            const struct ofputil_group_stats *gs)
7697 {
7698     size_t bucket_counter_size;
7699     struct ofp11_bucket_counter *bucket_counters;
7700     size_t length;
7701
7702     bucket_counter_size = gs->n_buckets * sizeof(struct ofp11_bucket_counter);
7703
7704     switch (ofpmp_version(replies)) {
7705     case OFP11_VERSION:
7706     case OFP12_VERSION:{
7707             struct ofp11_group_stats *gs11;
7708
7709             length = sizeof *gs11 + bucket_counter_size;
7710             gs11 = ofpmp_append(replies, length);
7711             bucket_counters = (struct ofp11_bucket_counter *)(gs11 + 1);
7712             ofputil_group_stats_to_ofp11(gs, gs11, length, bucket_counters);
7713             break;
7714         }
7715
7716     case OFP13_VERSION:
7717     case OFP14_VERSION:
7718     case OFP15_VERSION: {
7719             struct ofp13_group_stats *gs13;
7720
7721             length = sizeof *gs13 + bucket_counter_size;
7722             gs13 = ofpmp_append(replies, length);
7723             bucket_counters = (struct ofp11_bucket_counter *)(gs13 + 1);
7724             ofputil_group_stats_to_ofp13(gs, gs13, length, bucket_counters);
7725             break;
7726         }
7727
7728     case OFP10_VERSION:
7729     default:
7730         OVS_NOT_REACHED();
7731     }
7732 }
7733 /* Returns an OpenFlow group features request for OpenFlow version
7734  * 'ofp_version'. */
7735 struct ofpbuf *
7736 ofputil_encode_group_features_request(enum ofp_version ofp_version)
7737 {
7738     struct ofpbuf *request = NULL;
7739
7740     switch (ofp_version) {
7741     case OFP10_VERSION:
7742     case OFP11_VERSION:
7743         ovs_fatal(0, "dump-group-features needs OpenFlow 1.2 or later "
7744                      "(\'-O OpenFlow12\')");
7745     case OFP12_VERSION:
7746     case OFP13_VERSION:
7747     case OFP14_VERSION:
7748     case OFP15_VERSION:
7749         request = ofpraw_alloc(OFPRAW_OFPST12_GROUP_FEATURES_REQUEST,
7750                                ofp_version, 0);
7751         break;
7752     default:
7753         OVS_NOT_REACHED();
7754     }
7755
7756     return request;
7757 }
7758
7759 /* Returns a OpenFlow message that encodes 'features' properly as a reply to
7760  * group features request 'request'. */
7761 struct ofpbuf *
7762 ofputil_encode_group_features_reply(
7763     const struct ofputil_group_features *features,
7764     const struct ofp_header *request)
7765 {
7766     struct ofp12_group_features_stats *ogf;
7767     struct ofpbuf *reply;
7768     int i;
7769
7770     reply = ofpraw_alloc_xid(OFPRAW_OFPST12_GROUP_FEATURES_REPLY,
7771                              request->version, request->xid, 0);
7772     ogf = ofpbuf_put_zeros(reply, sizeof *ogf);
7773     ogf->types = htonl(features->types);
7774     ogf->capabilities = htonl(features->capabilities);
7775     for (i = 0; i < OFPGT12_N_TYPES; i++) {
7776         ogf->max_groups[i] = htonl(features->max_groups[i]);
7777         ogf->actions[i] = ofpact_bitmap_to_openflow(features->ofpacts[i],
7778                                                     request->version);
7779     }
7780
7781     return reply;
7782 }
7783
7784 /* Decodes group features reply 'oh' into 'features'. */
7785 void
7786 ofputil_decode_group_features_reply(const struct ofp_header *oh,
7787                                     struct ofputil_group_features *features)
7788 {
7789     const struct ofp12_group_features_stats *ogf = ofpmsg_body(oh);
7790     int i;
7791
7792     features->types = ntohl(ogf->types);
7793     features->capabilities = ntohl(ogf->capabilities);
7794     for (i = 0; i < OFPGT12_N_TYPES; i++) {
7795         features->max_groups[i] = ntohl(ogf->max_groups[i]);
7796         features->ofpacts[i] = ofpact_bitmap_from_openflow(
7797             ogf->actions[i], oh->version);
7798     }
7799 }
7800
7801 /* Parse a group status request message into a 32 bit OpenFlow 1.1
7802  * group ID and stores the latter in '*group_id'.
7803  * Returns 0 if successful, otherwise an OFPERR_* number. */
7804 enum ofperr
7805 ofputil_decode_group_stats_request(const struct ofp_header *request,
7806                                    uint32_t *group_id)
7807 {
7808     const struct ofp11_group_stats_request *gsr11 = ofpmsg_body(request);
7809     *group_id = ntohl(gsr11->group_id);
7810     return 0;
7811 }
7812
7813 /* Converts a group stats reply in 'msg' into an abstract ofputil_group_stats
7814  * in 'gs'.  Assigns freshly allocated memory to gs->bucket_stats for the
7815  * caller to eventually free.
7816  *
7817  * Multiple group stats replies can be packed into a single OpenFlow message.
7818  * Calling this function multiple times for a single 'msg' iterates through the
7819  * replies.  The caller must initially leave 'msg''s layer pointers null and
7820  * not modify them between calls.
7821  *
7822  * Returns 0 if successful, EOF if no replies were left in this 'msg',
7823  * otherwise a positive errno value. */
7824 int
7825 ofputil_decode_group_stats_reply(struct ofpbuf *msg,
7826                                  struct ofputil_group_stats *gs)
7827 {
7828     struct ofp11_bucket_counter *obc;
7829     struct ofp11_group_stats *ogs11;
7830     enum ofpraw raw;
7831     enum ofperr error;
7832     size_t base_len;
7833     size_t length;
7834     size_t i;
7835
7836     gs->bucket_stats = NULL;
7837     error = (msg->header ? ofpraw_decode(&raw, msg->header)
7838              : ofpraw_pull(&raw, msg));
7839     if (error) {
7840         return error;
7841     }
7842
7843     if (!msg->size) {
7844         return EOF;
7845     }
7846
7847     if (raw == OFPRAW_OFPST11_GROUP_REPLY) {
7848         base_len = sizeof *ogs11;
7849         ogs11 = ofpbuf_try_pull(msg, sizeof *ogs11);
7850         gs->duration_sec = gs->duration_nsec = UINT32_MAX;
7851     } else if (raw == OFPRAW_OFPST13_GROUP_REPLY) {
7852         struct ofp13_group_stats *ogs13;
7853
7854         base_len = sizeof *ogs13;
7855         ogs13 = ofpbuf_try_pull(msg, sizeof *ogs13);
7856         if (ogs13) {
7857             ogs11 = &ogs13->gs;
7858             gs->duration_sec = ntohl(ogs13->duration_sec);
7859             gs->duration_nsec = ntohl(ogs13->duration_nsec);
7860         } else {
7861             ogs11 = NULL;
7862         }
7863     } else {
7864         OVS_NOT_REACHED();
7865     }
7866
7867     if (!ogs11) {
7868         VLOG_WARN_RL(&bad_ofmsg_rl, "%s reply has %"PRIu32" leftover bytes at end",
7869                      ofpraw_get_name(raw), msg->size);
7870         return OFPERR_OFPBRC_BAD_LEN;
7871     }
7872     length = ntohs(ogs11->length);
7873     if (length < sizeof base_len) {
7874         VLOG_WARN_RL(&bad_ofmsg_rl, "%s reply claims invalid length %"PRIuSIZE,
7875                      ofpraw_get_name(raw), length);
7876         return OFPERR_OFPBRC_BAD_LEN;
7877     }
7878
7879     gs->group_id = ntohl(ogs11->group_id);
7880     gs->ref_count = ntohl(ogs11->ref_count);
7881     gs->packet_count = ntohll(ogs11->packet_count);
7882     gs->byte_count = ntohll(ogs11->byte_count);
7883
7884     gs->n_buckets = (length - base_len) / sizeof *obc;
7885     obc = ofpbuf_try_pull(msg, gs->n_buckets * sizeof *obc);
7886     if (!obc) {
7887         VLOG_WARN_RL(&bad_ofmsg_rl, "%s reply has %"PRIu32" leftover bytes at end",
7888                      ofpraw_get_name(raw), msg->size);
7889         return OFPERR_OFPBRC_BAD_LEN;
7890     }
7891
7892     gs->bucket_stats = xmalloc(gs->n_buckets * sizeof *gs->bucket_stats);
7893     for (i = 0; i < gs->n_buckets; i++) {
7894         gs->bucket_stats[i].packet_count = ntohll(obc[i].packet_count);
7895         gs->bucket_stats[i].byte_count = ntohll(obc[i].byte_count);
7896     }
7897
7898     return 0;
7899 }
7900
7901 static void
7902 ofputil_put_ofp11_bucket(const struct ofputil_bucket *bucket,
7903                          struct ofpbuf *openflow, enum ofp_version ofp_version)
7904 {
7905     struct ofp11_bucket *ob;
7906     size_t start;
7907
7908     start = openflow->size;
7909     ofpbuf_put_zeros(openflow, sizeof *ob);
7910     ofpacts_put_openflow_actions(bucket->ofpacts, bucket->ofpacts_len,
7911                                 openflow, ofp_version);
7912     ob = ofpbuf_at_assert(openflow, start, sizeof *ob);
7913     ob->len = htons(openflow->size - start);
7914     ob->weight = htons(bucket->weight);
7915     ob->watch_port = ofputil_port_to_ofp11(bucket->watch_port);
7916     ob->watch_group = htonl(bucket->watch_group);
7917 }
7918
7919 static void
7920 ofputil_put_ofp15_bucket(const struct ofputil_bucket *bucket,
7921                          uint32_t bucket_id, enum ofp11_group_type group_type,
7922                          struct ofpbuf *openflow, enum ofp_version ofp_version)
7923 {
7924     struct ofp15_bucket *ob;
7925     size_t start, actions_start, actions_len;
7926
7927     start = openflow->size;
7928     ofpbuf_put_zeros(openflow, sizeof *ob);
7929
7930     actions_start = openflow->size;
7931     ofpacts_put_openflow_actions(bucket->ofpacts, bucket->ofpacts_len,
7932                                  openflow, ofp_version);
7933     actions_len = openflow->size - actions_start;
7934
7935     if (group_type == OFPGT11_SELECT) {
7936         ofpprop_put_u16(openflow, OFPGBPT15_WEIGHT, bucket->weight);
7937     }
7938     if (bucket->watch_port != OFPP_ANY) {
7939         ofpprop_put_be32(openflow, OFPGBPT15_WATCH_PORT,
7940                          ofputil_port_to_ofp11(bucket->watch_port));
7941     }
7942     if (bucket->watch_group != OFPG_ANY) {
7943         ofpprop_put_u32(openflow, OFPGBPT15_WATCH_GROUP, bucket->watch_group);
7944     }
7945
7946     ob = ofpbuf_at_assert(openflow, start, sizeof *ob);
7947     ob->len = htons(openflow->size - start);
7948     ob->action_array_len = htons(actions_len);
7949     ob->bucket_id = htonl(bucket_id);
7950 }
7951
7952 static void
7953 ofputil_put_group_prop_ntr_selection_method(enum ofp_version ofp_version,
7954                                             const struct ofputil_group_props *gp,
7955                                             struct ofpbuf *openflow)
7956 {
7957     struct ntr_group_prop_selection_method *prop;
7958     size_t start;
7959
7960     start = openflow->size;
7961     ofpbuf_put_zeros(openflow, sizeof *prop);
7962     oxm_put_field_array(openflow, &gp->fields, ofp_version);
7963     prop = ofpbuf_at_assert(openflow, start, sizeof *prop);
7964     prop->type = htons(OFPGPT15_EXPERIMENTER);
7965     prop->experimenter = htonl(NTR_VENDOR_ID);
7966     prop->exp_type = htonl(NTRT_SELECTION_METHOD);
7967     strcpy(prop->selection_method, gp->selection_method);
7968     prop->selection_method_param = htonll(gp->selection_method_param);
7969     ofpprop_end(openflow, start);
7970 }
7971
7972 static void
7973 ofputil_append_ofp11_group_desc_reply(const struct ofputil_group_desc *gds,
7974                                       const struct ovs_list *buckets,
7975                                       struct ovs_list *replies,
7976                                       enum ofp_version version)
7977 {
7978     struct ofpbuf *reply = ofpbuf_from_list(list_back(replies));
7979     struct ofp11_group_desc_stats *ogds;
7980     struct ofputil_bucket *bucket;
7981     size_t start_ogds;
7982
7983     start_ogds = reply->size;
7984     ofpbuf_put_zeros(reply, sizeof *ogds);
7985     LIST_FOR_EACH (bucket, list_node, buckets) {
7986         ofputil_put_ofp11_bucket(bucket, reply, version);
7987     }
7988     ogds = ofpbuf_at_assert(reply, start_ogds, sizeof *ogds);
7989     ogds->length = htons(reply->size - start_ogds);
7990     ogds->type = gds->type;
7991     ogds->group_id = htonl(gds->group_id);
7992
7993     ofpmp_postappend(replies, start_ogds);
7994 }
7995
7996 static void
7997 ofputil_append_ofp15_group_desc_reply(const struct ofputil_group_desc *gds,
7998                                       const struct ovs_list *buckets,
7999                                       struct ovs_list *replies,
8000                                       enum ofp_version version)
8001 {
8002     struct ofpbuf *reply = ofpbuf_from_list(list_back(replies));
8003     struct ofp15_group_desc_stats *ogds;
8004     struct ofputil_bucket *bucket;
8005     size_t start_ogds, start_buckets;
8006
8007     start_ogds = reply->size;
8008     ofpbuf_put_zeros(reply, sizeof *ogds);
8009     start_buckets = reply->size;
8010     LIST_FOR_EACH (bucket, list_node, buckets) {
8011         ofputil_put_ofp15_bucket(bucket, bucket->bucket_id,
8012                                  gds->type, reply, version);
8013     }
8014     ogds = ofpbuf_at_assert(reply, start_ogds, sizeof *ogds);
8015     ogds->type = gds->type;
8016     ogds->group_id = htonl(gds->group_id);
8017     ogds->bucket_list_len =  htons(reply->size - start_buckets);
8018
8019     /* Add group properties */
8020     if (gds->props.selection_method[0]) {
8021         ofputil_put_group_prop_ntr_selection_method(version, &gds->props,
8022                                                     reply);
8023     }
8024     ogds->length = htons(reply->size - start_ogds);
8025
8026     ofpmp_postappend(replies, start_ogds);
8027 }
8028
8029 /* Appends a group stats reply that contains the data in 'gds' to those already
8030  * present in the list of ofpbufs in 'replies'.  'replies' should have been
8031  * initialized with ofpmp_init(). */
8032 void
8033 ofputil_append_group_desc_reply(const struct ofputil_group_desc *gds,
8034                                 const struct ovs_list *buckets,
8035                                 struct ovs_list *replies)
8036 {
8037     enum ofp_version version = ofpmp_version(replies);
8038
8039     switch (version)
8040     {
8041     case OFP11_VERSION:
8042     case OFP12_VERSION:
8043     case OFP13_VERSION:
8044     case OFP14_VERSION:
8045         ofputil_append_ofp11_group_desc_reply(gds, buckets, replies, version);
8046         break;
8047
8048     case OFP15_VERSION:
8049         ofputil_append_ofp15_group_desc_reply(gds, buckets, replies, version);
8050         break;
8051
8052     case OFP10_VERSION:
8053     default:
8054         OVS_NOT_REACHED();
8055     }
8056 }
8057
8058 static enum ofperr
8059 ofputil_pull_ofp11_buckets(struct ofpbuf *msg, size_t buckets_length,
8060                            enum ofp_version version, struct ovs_list *buckets)
8061 {
8062     struct ofp11_bucket *ob;
8063     uint32_t bucket_id = 0;
8064
8065     list_init(buckets);
8066     while (buckets_length > 0) {
8067         struct ofputil_bucket *bucket;
8068         struct ofpbuf ofpacts;
8069         enum ofperr error;
8070         size_t ob_len;
8071
8072         ob = (buckets_length >= sizeof *ob
8073               ? ofpbuf_try_pull(msg, sizeof *ob)
8074               : NULL);
8075         if (!ob) {
8076             VLOG_WARN_RL(&bad_ofmsg_rl, "buckets end with %"PRIuSIZE" leftover bytes",
8077                          buckets_length);
8078             return OFPERR_OFPGMFC_BAD_BUCKET;
8079         }
8080
8081         ob_len = ntohs(ob->len);
8082         if (ob_len < sizeof *ob) {
8083             VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message bucket length "
8084                          "%"PRIuSIZE" is not valid", ob_len);
8085             return OFPERR_OFPGMFC_BAD_BUCKET;
8086         } else if (ob_len > buckets_length) {
8087             VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message bucket length "
8088                          "%"PRIuSIZE" exceeds remaining buckets data size %"PRIuSIZE,
8089                          ob_len, buckets_length);
8090             return OFPERR_OFPGMFC_BAD_BUCKET;
8091         }
8092         buckets_length -= ob_len;
8093
8094         ofpbuf_init(&ofpacts, 0);
8095         error = ofpacts_pull_openflow_actions(msg, ob_len - sizeof *ob,
8096                                               version, &ofpacts);
8097         if (error) {
8098             ofpbuf_uninit(&ofpacts);
8099             ofputil_bucket_list_destroy(buckets);
8100             return error;
8101         }
8102
8103         bucket = xzalloc(sizeof *bucket);
8104         bucket->weight = ntohs(ob->weight);
8105         error = ofputil_port_from_ofp11(ob->watch_port, &bucket->watch_port);
8106         if (error) {
8107             ofpbuf_uninit(&ofpacts);
8108             ofputil_bucket_list_destroy(buckets);
8109             return OFPERR_OFPGMFC_BAD_WATCH;
8110         }
8111         bucket->watch_group = ntohl(ob->watch_group);
8112         bucket->bucket_id = bucket_id++;
8113
8114         bucket->ofpacts = ofpbuf_steal_data(&ofpacts);
8115         bucket->ofpacts_len = ofpacts.size;
8116         list_push_back(buckets, &bucket->list_node);
8117     }
8118
8119     return 0;
8120 }
8121
8122 static enum ofperr
8123 ofputil_pull_ofp15_buckets(struct ofpbuf *msg, size_t buckets_length,
8124                            enum ofp_version version, uint8_t group_type,
8125                            struct ovs_list *buckets)
8126 {
8127     struct ofp15_bucket *ob;
8128
8129     list_init(buckets);
8130     while (buckets_length > 0) {
8131         struct ofputil_bucket *bucket = NULL;
8132         struct ofpbuf ofpacts;
8133         enum ofperr err = OFPERR_OFPGMFC_BAD_BUCKET;
8134         size_t ob_len, actions_len, properties_len;
8135         ovs_be32 watch_port = ofputil_port_to_ofp11(OFPP_ANY);
8136         ovs_be32 watch_group = htonl(OFPG_ANY);
8137         ovs_be16 weight = htons(group_type == OFPGT11_SELECT ? 1 : 0);
8138
8139         ofpbuf_init(&ofpacts, 0);
8140
8141         ob = ofpbuf_try_pull(msg, sizeof *ob);
8142         if (!ob) {
8143             VLOG_WARN_RL(&bad_ofmsg_rl, "buckets end with %"PRIuSIZE
8144                          " leftover bytes", buckets_length);
8145             goto err;
8146         }
8147
8148         ob_len = ntohs(ob->len);
8149         actions_len = ntohs(ob->action_array_len);
8150
8151         if (ob_len < sizeof *ob) {
8152             VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message bucket length "
8153                          "%"PRIuSIZE" is not valid", ob_len);
8154             goto err;
8155         } else if (ob_len > buckets_length) {
8156             VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message bucket length "
8157                          "%"PRIuSIZE" exceeds remaining buckets data size %"
8158                          PRIuSIZE, ob_len, buckets_length);
8159             goto err;
8160         } else if (actions_len > ob_len - sizeof *ob) {
8161             VLOG_WARN_RL(&bad_ofmsg_rl, "OpenFlow message bucket actions "
8162                          "length %"PRIuSIZE" exceeds remaining bucket "
8163                          "data size %"PRIuSIZE, actions_len,
8164                          ob_len - sizeof *ob);
8165             goto err;
8166         }
8167         buckets_length -= ob_len;
8168
8169         err = ofpacts_pull_openflow_actions(msg, actions_len, version,
8170                                             &ofpacts);
8171         if (err) {
8172             goto err;
8173         }
8174
8175         properties_len = ob_len - sizeof *ob - actions_len;
8176         struct ofpbuf properties = ofpbuf_const_initializer(
8177             ofpbuf_pull(msg, properties_len), properties_len);
8178         while (properties.size > 0) {
8179             struct ofpbuf payload;
8180             uint64_t type;
8181
8182             err = ofpprop_pull(&properties, &payload, &type);
8183             if (err) {
8184                 goto err;
8185             }
8186
8187             switch (type) {
8188             case OFPGBPT15_WEIGHT:
8189                 err = ofpprop_parse_be16(&payload, &weight);
8190                 break;
8191
8192             case OFPGBPT15_WATCH_PORT:
8193                 err = ofpprop_parse_be32(&payload, &watch_port);
8194                 break;
8195
8196             case OFPGBPT15_WATCH_GROUP:
8197                 err = ofpprop_parse_be32(&payload, &watch_group);
8198                 break;
8199
8200             default:
8201                 err = OFPPROP_UNKNOWN(false, "group bucket", type);
8202                 break;
8203             }
8204
8205             if (err) {
8206                 goto err;
8207             }
8208         }
8209
8210         bucket = xzalloc(sizeof *bucket);
8211
8212         bucket->weight = ntohs(weight);
8213         err = ofputil_port_from_ofp11(watch_port, &bucket->watch_port);
8214         if (err) {
8215             err = OFPERR_OFPGMFC_BAD_WATCH;
8216             goto err;
8217         }
8218         bucket->watch_group = ntohl(watch_group);
8219         bucket->bucket_id = ntohl(ob->bucket_id);
8220         if (bucket->bucket_id > OFPG15_BUCKET_MAX) {
8221             VLOG_WARN_RL(&bad_ofmsg_rl, "bucket id (%u) is out of range",
8222                          bucket->bucket_id);
8223             err = OFPERR_OFPGMFC_BAD_BUCKET;
8224             goto err;
8225         }
8226
8227         bucket->ofpacts = ofpbuf_steal_data(&ofpacts);
8228         bucket->ofpacts_len = ofpacts.size;
8229         list_push_back(buckets, &bucket->list_node);
8230
8231         continue;
8232
8233     err:
8234         free(bucket);
8235         ofpbuf_uninit(&ofpacts);
8236         ofputil_bucket_list_destroy(buckets);
8237         return err;
8238     }
8239
8240     if (ofputil_bucket_check_duplicate_id(buckets)) {
8241         VLOG_WARN_RL(&bad_ofmsg_rl, "Duplicate bucket id");
8242         ofputil_bucket_list_destroy(buckets);
8243         return OFPERR_OFPGMFC_BAD_BUCKET;
8244     }
8245
8246     return 0;
8247 }
8248
8249 static void
8250 ofputil_init_group_properties(struct ofputil_group_props *gp)
8251 {
8252     memset(gp, 0, sizeof *gp);
8253 }
8254
8255 static enum ofperr
8256 parse_group_prop_ntr_selection_method(struct ofpbuf *payload,
8257                                       enum ofp11_group_type group_type,
8258                                       enum ofp15_group_mod_command group_cmd,
8259                                       struct ofputil_group_props *gp)
8260 {
8261     struct ntr_group_prop_selection_method *prop = payload->data;
8262     size_t fields_len, method_len;
8263     enum ofperr error;
8264
8265     switch (group_type) {
8266     case OFPGT11_SELECT:
8267         break;
8268     case OFPGT11_ALL:
8269     case OFPGT11_INDIRECT:
8270     case OFPGT11_FF:
8271         OFPPROP_LOG(&bad_ofmsg_rl, false, "ntr selection method property is "
8272                     "only allowed for select groups");
8273         return OFPERR_OFPBPC_BAD_VALUE;
8274     default:
8275         OVS_NOT_REACHED();
8276     }
8277
8278     switch (group_cmd) {
8279     case OFPGC15_ADD:
8280     case OFPGC15_MODIFY:
8281         break;
8282     case OFPGC15_DELETE:
8283     case OFPGC15_INSERT_BUCKET:
8284     case OFPGC15_REMOVE_BUCKET:
8285         OFPPROP_LOG(&bad_ofmsg_rl, false, "ntr selection method property is "
8286                     "only allowed for add and delete group modifications");
8287         return OFPERR_OFPBPC_BAD_VALUE;
8288     default:
8289         OVS_NOT_REACHED();
8290     }
8291
8292     if (payload->size < sizeof *prop) {
8293         OFPPROP_LOG(&bad_ofmsg_rl, false, "ntr selection method property "
8294                     "length %u is not valid", payload->size);
8295         return OFPERR_OFPBPC_BAD_LEN;
8296     }
8297
8298     method_len = strnlen(prop->selection_method, NTR_MAX_SELECTION_METHOD_LEN);
8299
8300     if (method_len == NTR_MAX_SELECTION_METHOD_LEN) {
8301         OFPPROP_LOG(&bad_ofmsg_rl, false,
8302                     "ntr selection method is not null terminated");
8303         return OFPERR_OFPBPC_BAD_VALUE;
8304     }
8305
8306     if (strcmp("hash", prop->selection_method)) {
8307         OFPPROP_LOG(&bad_ofmsg_rl, false,
8308                     "ntr selection method '%s' is not supported",
8309                     prop->selection_method);
8310         return OFPERR_OFPBPC_BAD_VALUE;
8311     }
8312
8313     strcpy(gp->selection_method, prop->selection_method);
8314     gp->selection_method_param = ntohll(prop->selection_method_param);
8315
8316     if (!method_len && gp->selection_method_param) {
8317         OFPPROP_LOG(&bad_ofmsg_rl, false, "ntr selection method parameter is "
8318                     "non-zero but selection method is empty");
8319         return OFPERR_OFPBPC_BAD_VALUE;
8320     }
8321
8322     ofpbuf_pull(payload, sizeof *prop);
8323
8324     fields_len = ntohs(prop->length) - sizeof *prop;
8325     if (!method_len && fields_len) {
8326         OFPPROP_LOG(&bad_ofmsg_rl, false, "ntr selection method parameter is "
8327                     "zero but fields are provided");
8328         return OFPERR_OFPBPC_BAD_VALUE;
8329     }
8330
8331     error = oxm_pull_field_array(payload->data, fields_len,
8332                                  &gp->fields);
8333     if (error) {
8334         OFPPROP_LOG(&bad_ofmsg_rl, false,
8335                     "ntr selection method fields are invalid");
8336         return error;
8337     }
8338
8339     return 0;
8340 }
8341
8342 static enum ofperr
8343 parse_ofp15_group_properties(struct ofpbuf *msg,
8344                              enum ofp11_group_type group_type,
8345                              enum ofp15_group_mod_command group_cmd,
8346                              struct ofputil_group_props *gp,
8347                              size_t properties_len)
8348 {
8349     struct ofpbuf properties = ofpbuf_const_initializer(
8350         ofpbuf_pull(msg, properties_len), properties_len);
8351     while (properties.size > 0) {
8352         struct ofpbuf payload;
8353         enum ofperr error;
8354         uint64_t type;
8355
8356         error = ofpprop_pull(&properties, &payload, &type);
8357         if (error) {
8358             return error;
8359         }
8360
8361         switch (type) {
8362         case OFPPROP_EXP(NTR_VENDOR_ID, NTRT_SELECTION_METHOD):
8363         case OFPPROP_EXP(NTR_COMPAT_VENDOR_ID, NTRT_SELECTION_METHOD):
8364             error = parse_group_prop_ntr_selection_method(&payload, group_type,
8365                                                           group_cmd, gp);
8366             break;
8367
8368         default:
8369             error = OFPPROP_UNKNOWN(false, "group", type);
8370             break;
8371         }
8372
8373         if (error) {
8374             return error;
8375         }
8376     }
8377
8378     return 0;
8379 }
8380
8381 static int
8382 ofputil_decode_ofp11_group_desc_reply(struct ofputil_group_desc *gd,
8383                                       struct ofpbuf *msg,
8384                                       enum ofp_version version)
8385 {
8386     struct ofp11_group_desc_stats *ogds;
8387     size_t length;
8388
8389     if (!msg->header) {
8390         ofpraw_pull_assert(msg);
8391     }
8392
8393     if (!msg->size) {
8394         return EOF;
8395     }
8396
8397     ogds = ofpbuf_try_pull(msg, sizeof *ogds);
8398     if (!ogds) {
8399         VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST11_GROUP_DESC reply has %"PRIu32" "
8400                      "leftover bytes at end", msg->size);
8401         return OFPERR_OFPBRC_BAD_LEN;
8402     }
8403     gd->type = ogds->type;
8404     gd->group_id = ntohl(ogds->group_id);
8405
8406     length = ntohs(ogds->length);
8407     if (length < sizeof *ogds || length - sizeof *ogds > msg->size) {
8408         VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST11_GROUP_DESC reply claims invalid "
8409                      "length %"PRIuSIZE, length);
8410         return OFPERR_OFPBRC_BAD_LEN;
8411     }
8412
8413     return ofputil_pull_ofp11_buckets(msg, length - sizeof *ogds, version,
8414                                       &gd->buckets);
8415 }
8416
8417 static int
8418 ofputil_decode_ofp15_group_desc_reply(struct ofputil_group_desc *gd,
8419                                       struct ofpbuf *msg,
8420                                       enum ofp_version version)
8421 {
8422     struct ofp15_group_desc_stats *ogds;
8423     uint16_t length, bucket_list_len;
8424     int error;
8425
8426     if (!msg->header) {
8427         ofpraw_pull_assert(msg);
8428     }
8429
8430     if (!msg->size) {
8431         return EOF;
8432     }
8433
8434     ogds = ofpbuf_try_pull(msg, sizeof *ogds);
8435     if (!ogds) {
8436         VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST11_GROUP_DESC reply has %"PRIu32" "
8437                      "leftover bytes at end", msg->size);
8438         return OFPERR_OFPBRC_BAD_LEN;
8439     }
8440     gd->type = ogds->type;
8441     gd->group_id = ntohl(ogds->group_id);
8442
8443     length = ntohs(ogds->length);
8444     if (length < sizeof *ogds || length - sizeof *ogds > msg->size) {
8445         VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST11_GROUP_DESC reply claims invalid "
8446                      "length %u", length);
8447         return OFPERR_OFPBRC_BAD_LEN;
8448     }
8449
8450     bucket_list_len = ntohs(ogds->bucket_list_len);
8451     if (length < bucket_list_len + sizeof *ogds) {
8452         VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST11_GROUP_DESC reply claims invalid "
8453                      "bucket list length %u", bucket_list_len);
8454         return OFPERR_OFPBRC_BAD_LEN;
8455     }
8456     error = ofputil_pull_ofp15_buckets(msg, bucket_list_len, version, gd->type,
8457                                        &gd->buckets);
8458     if (error) {
8459         return error;
8460     }
8461
8462     /* By definition group desc messages don't have a group mod command.
8463      * However, parse_group_prop_ntr_selection_method() checks to make sure
8464      * that the command is OFPGC15_ADD or OFPGC15_DELETE to guard
8465      * against group mod messages with other commands supplying
8466      * a NTR selection method group experimenter property.
8467      * Such properties are valid for group desc replies so
8468      * claim that the group mod command is OFPGC15_ADD to
8469      * satisfy the check in parse_group_prop_ntr_selection_method() */
8470     return parse_ofp15_group_properties(msg, gd->type, OFPGC15_ADD, &gd->props,
8471                                         length - sizeof *ogds - bucket_list_len);
8472 }
8473
8474 /* Converts a group description reply in 'msg' into an abstract
8475  * ofputil_group_desc in 'gd'.
8476  *
8477  * Multiple group description replies can be packed into a single OpenFlow
8478  * message.  Calling this function multiple times for a single 'msg' iterates
8479  * through the replies.  The caller must initially leave 'msg''s layer pointers
8480  * null and not modify them between calls.
8481  *
8482  * Returns 0 if successful, EOF if no replies were left in this 'msg',
8483  * otherwise a positive errno value. */
8484 int
8485 ofputil_decode_group_desc_reply(struct ofputil_group_desc *gd,
8486                                 struct ofpbuf *msg, enum ofp_version version)
8487 {
8488     ofputil_init_group_properties(&gd->props);
8489
8490     switch (version)
8491     {
8492     case OFP11_VERSION:
8493     case OFP12_VERSION:
8494     case OFP13_VERSION:
8495     case OFP14_VERSION:
8496         return ofputil_decode_ofp11_group_desc_reply(gd, msg, version);
8497
8498     case OFP15_VERSION:
8499         return ofputil_decode_ofp15_group_desc_reply(gd, msg, version);
8500
8501     case OFP10_VERSION:
8502     default:
8503         OVS_NOT_REACHED();
8504     }
8505 }
8506
8507 void
8508 ofputil_uninit_group_mod(struct ofputil_group_mod *gm)
8509 {
8510     ofputil_bucket_list_destroy(&gm->buckets);
8511 }
8512
8513 static struct ofpbuf *
8514 ofputil_encode_ofp11_group_mod(enum ofp_version ofp_version,
8515                                const struct ofputil_group_mod *gm)
8516 {
8517     struct ofpbuf *b;
8518     struct ofp11_group_mod *ogm;
8519     size_t start_ogm;
8520     struct ofputil_bucket *bucket;
8521
8522     b = ofpraw_alloc(OFPRAW_OFPT11_GROUP_MOD, ofp_version, 0);
8523     start_ogm = b->size;
8524     ofpbuf_put_zeros(b, sizeof *ogm);
8525
8526     LIST_FOR_EACH (bucket, list_node, &gm->buckets) {
8527         ofputil_put_ofp11_bucket(bucket, b, ofp_version);
8528     }
8529     ogm = ofpbuf_at_assert(b, start_ogm, sizeof *ogm);
8530     ogm->command = htons(gm->command);
8531     ogm->type = gm->type;
8532     ogm->group_id = htonl(gm->group_id);
8533
8534     return b;
8535 }
8536
8537 static struct ofpbuf *
8538 ofputil_encode_ofp15_group_mod(enum ofp_version ofp_version,
8539                                const struct ofputil_group_mod *gm)
8540 {
8541     struct ofpbuf *b;
8542     struct ofp15_group_mod *ogm;
8543     size_t start_ogm;
8544     struct ofputil_bucket *bucket;
8545     struct id_pool *bucket_ids = NULL;
8546
8547     b = ofpraw_alloc(OFPRAW_OFPT15_GROUP_MOD, ofp_version, 0);
8548     start_ogm = b->size;
8549     ofpbuf_put_zeros(b, sizeof *ogm);
8550
8551     LIST_FOR_EACH (bucket, list_node, &gm->buckets) {
8552         uint32_t bucket_id;
8553
8554         /* Generate a bucket id if none was supplied */
8555         if (bucket->bucket_id > OFPG15_BUCKET_MAX) {
8556             if (!bucket_ids) {
8557                 const struct ofputil_bucket *bkt;
8558
8559                 bucket_ids = id_pool_create(0, OFPG15_BUCKET_MAX + 1);
8560
8561                 /* Mark all bucket_ids that are present in gm
8562                  * as used in the pool. */
8563                 LIST_FOR_EACH_REVERSE (bkt, list_node, &gm->buckets) {
8564                     if (bkt == bucket) {
8565                         break;
8566                     }
8567                     if (bkt->bucket_id <= OFPG15_BUCKET_MAX) {
8568                         id_pool_add(bucket_ids, bkt->bucket_id);
8569                     }
8570                 }
8571             }
8572
8573             if (!id_pool_alloc_id(bucket_ids, &bucket_id)) {
8574                 OVS_NOT_REACHED();
8575             }
8576         } else {
8577             bucket_id = bucket->bucket_id;
8578         }
8579
8580         ofputil_put_ofp15_bucket(bucket, bucket_id, gm->type, b, ofp_version);
8581     }
8582     ogm = ofpbuf_at_assert(b, start_ogm, sizeof *ogm);
8583     ogm->command = htons(gm->command);
8584     ogm->type = gm->type;
8585     ogm->group_id = htonl(gm->group_id);
8586     ogm->command_bucket_id = htonl(gm->command_bucket_id);
8587     ogm->bucket_array_len = htons(b->size - start_ogm - sizeof *ogm);
8588
8589     /* Add group properties */
8590     if (gm->props.selection_method[0]) {
8591         ofputil_put_group_prop_ntr_selection_method(ofp_version, &gm->props, b);
8592     }
8593
8594     id_pool_destroy(bucket_ids);
8595     return b;
8596 }
8597
8598 static void
8599 bad_group_cmd(enum ofp15_group_mod_command cmd)
8600 {
8601     const char *opt_version;
8602     const char *version;
8603     const char *cmd_str;
8604
8605     switch (cmd) {
8606     case OFPGC15_ADD:
8607     case OFPGC15_MODIFY:
8608     case OFPGC15_DELETE:
8609         version = "1.1";
8610         opt_version = "11";
8611         break;
8612
8613     case OFPGC15_INSERT_BUCKET:
8614     case OFPGC15_REMOVE_BUCKET:
8615         version = "1.5";
8616         opt_version = "15";
8617         break;
8618
8619     default:
8620         OVS_NOT_REACHED();
8621     }
8622
8623     switch (cmd) {
8624     case OFPGC15_ADD:
8625         cmd_str = "add-group";
8626         break;
8627
8628     case OFPGC15_MODIFY:
8629         cmd_str = "mod-group";
8630         break;
8631
8632     case OFPGC15_DELETE:
8633         cmd_str = "del-group";
8634         break;
8635
8636     case OFPGC15_INSERT_BUCKET:
8637         cmd_str = "insert-bucket";
8638         break;
8639
8640     case OFPGC15_REMOVE_BUCKET:
8641         cmd_str = "remove-bucket";
8642         break;
8643
8644     default:
8645         OVS_NOT_REACHED();
8646     }
8647
8648     ovs_fatal(0, "%s needs OpenFlow %s or later (\'-O OpenFlow%s\')",
8649               cmd_str, version, opt_version);
8650
8651 }
8652
8653 /* Converts abstract group mod 'gm' into a message for OpenFlow version
8654  * 'ofp_version' and returns the message. */
8655 struct ofpbuf *
8656 ofputil_encode_group_mod(enum ofp_version ofp_version,
8657                          const struct ofputil_group_mod *gm)
8658 {
8659
8660     switch (ofp_version) {
8661     case OFP10_VERSION:
8662         bad_group_cmd(gm->command);
8663
8664     case OFP11_VERSION:
8665     case OFP12_VERSION:
8666     case OFP13_VERSION:
8667     case OFP14_VERSION:
8668         if (gm->command > OFPGC11_DELETE) {
8669             bad_group_cmd(gm->command);
8670         }
8671         return ofputil_encode_ofp11_group_mod(ofp_version, gm);
8672
8673     case OFP15_VERSION:
8674         return ofputil_encode_ofp15_group_mod(ofp_version, gm);
8675
8676     default:
8677         OVS_NOT_REACHED();
8678     }
8679 }
8680
8681 static enum ofperr
8682 ofputil_pull_ofp11_group_mod(struct ofpbuf *msg, enum ofp_version ofp_version,
8683                              struct ofputil_group_mod *gm)
8684 {
8685     const struct ofp11_group_mod *ogm;
8686     enum ofperr error;
8687
8688     ogm = ofpbuf_pull(msg, sizeof *ogm);
8689     gm->command = ntohs(ogm->command);
8690     gm->type = ogm->type;
8691     gm->group_id = ntohl(ogm->group_id);
8692     gm->command_bucket_id = OFPG15_BUCKET_ALL;
8693
8694     error = ofputil_pull_ofp11_buckets(msg, msg->size, ofp_version,
8695                                        &gm->buckets);
8696
8697     /* OF1.3.5+ prescribes an error when an OFPGC_DELETE includes buckets. */
8698     if (!error
8699         && ofp_version >= OFP13_VERSION
8700         && gm->command == OFPGC11_DELETE
8701         && !list_is_empty(&gm->buckets)) {
8702         error = OFPERR_OFPGMFC_INVALID_GROUP;
8703     }
8704
8705     return error;
8706 }
8707
8708 static enum ofperr
8709 ofputil_pull_ofp15_group_mod(struct ofpbuf *msg, enum ofp_version ofp_version,
8710                              struct ofputil_group_mod *gm)
8711 {
8712     const struct ofp15_group_mod *ogm;
8713     uint16_t bucket_list_len;
8714     enum ofperr error = OFPERR_OFPGMFC_BAD_BUCKET;
8715
8716     ogm = ofpbuf_pull(msg, sizeof *ogm);
8717     gm->command = ntohs(ogm->command);
8718     gm->type = ogm->type;
8719     gm->group_id = ntohl(ogm->group_id);
8720
8721     gm->command_bucket_id = ntohl(ogm->command_bucket_id);
8722     switch (gm->command) {
8723     case OFPGC15_REMOVE_BUCKET:
8724         if (gm->command_bucket_id == OFPG15_BUCKET_ALL) {
8725             error = 0;
8726         }
8727         /* Fall through */
8728     case OFPGC15_INSERT_BUCKET:
8729         if (gm->command_bucket_id <= OFPG15_BUCKET_MAX ||
8730             gm->command_bucket_id == OFPG15_BUCKET_FIRST
8731             || gm->command_bucket_id == OFPG15_BUCKET_LAST) {
8732             error = 0;
8733         }
8734         break;
8735
8736     case OFPGC11_ADD:
8737     case OFPGC11_MODIFY:
8738     case OFPGC11_DELETE:
8739     default:
8740         if (gm->command_bucket_id == OFPG15_BUCKET_ALL) {
8741             error = 0;
8742         }
8743         break;
8744     }
8745     if (error) {
8746         VLOG_WARN_RL(&bad_ofmsg_rl,
8747                      "group command bucket id (%u) is out of range",
8748                      gm->command_bucket_id);
8749         return OFPERR_OFPGMFC_BAD_BUCKET;
8750     }
8751
8752     bucket_list_len = ntohs(ogm->bucket_array_len);
8753     error = ofputil_pull_ofp15_buckets(msg, bucket_list_len, ofp_version,
8754                                        gm->type, &gm->buckets);
8755     if (error) {
8756         return error;
8757     }
8758
8759     return parse_ofp15_group_properties(msg, gm->type, gm->command, &gm->props,
8760                                         msg->size);
8761 }
8762
8763 /* Converts OpenFlow group mod message 'oh' into an abstract group mod in
8764  * 'gm'.  Returns 0 if successful, otherwise an OpenFlow error code. */
8765 enum ofperr
8766 ofputil_decode_group_mod(const struct ofp_header *oh,
8767                          struct ofputil_group_mod *gm)
8768 {
8769     ofputil_init_group_properties(&gm->props);
8770
8771     enum ofp_version ofp_version = oh->version;
8772     struct ofpbuf msg = ofpbuf_const_initializer(oh, ntohs(oh->length));
8773     ofpraw_pull_assert(&msg);
8774
8775     enum ofperr err;
8776     switch (ofp_version)
8777     {
8778     case OFP11_VERSION:
8779     case OFP12_VERSION:
8780     case OFP13_VERSION:
8781     case OFP14_VERSION:
8782         err = ofputil_pull_ofp11_group_mod(&msg, ofp_version, gm);
8783         break;
8784
8785     case OFP15_VERSION:
8786         err = ofputil_pull_ofp15_group_mod(&msg, ofp_version, gm);
8787         break;
8788
8789     case OFP10_VERSION:
8790     default:
8791         OVS_NOT_REACHED();
8792     }
8793     if (err) {
8794         return err;
8795     }
8796
8797     switch (gm->type) {
8798     case OFPGT11_INDIRECT:
8799         if (!list_is_singleton(&gm->buckets)) {
8800             return OFPERR_OFPGMFC_INVALID_GROUP;
8801         }
8802         break;
8803     case OFPGT11_ALL:
8804     case OFPGT11_SELECT:
8805     case OFPGT11_FF:
8806         break;
8807     default:
8808         return OFPERR_OFPGMFC_BAD_TYPE;
8809     }
8810
8811     switch (gm->command) {
8812     case OFPGC11_ADD:
8813     case OFPGC11_MODIFY:
8814     case OFPGC11_DELETE:
8815     case OFPGC15_INSERT_BUCKET:
8816         break;
8817     case OFPGC15_REMOVE_BUCKET:
8818         if (!list_is_empty(&gm->buckets)) {
8819             return OFPERR_OFPGMFC_BAD_BUCKET;
8820         }
8821         break;
8822     default:
8823         return OFPERR_OFPGMFC_BAD_COMMAND;
8824     }
8825
8826     struct ofputil_bucket *bucket;
8827     LIST_FOR_EACH (bucket, list_node, &gm->buckets) {
8828         if (bucket->weight && gm->type != OFPGT11_SELECT) {
8829             return OFPERR_OFPGMFC_INVALID_GROUP;
8830         }
8831
8832         switch (gm->type) {
8833         case OFPGT11_ALL:
8834         case OFPGT11_INDIRECT:
8835             if (ofputil_bucket_has_liveness(bucket)) {
8836                 return OFPERR_OFPGMFC_WATCH_UNSUPPORTED;
8837             }
8838             break;
8839         case OFPGT11_SELECT:
8840             break;
8841         case OFPGT11_FF:
8842             if (!ofputil_bucket_has_liveness(bucket)) {
8843                 return OFPERR_OFPGMFC_INVALID_GROUP;
8844             }
8845             break;
8846         default:
8847             /* Returning BAD TYPE to be consistent
8848              * though gm->type has been checked already. */
8849             return OFPERR_OFPGMFC_BAD_TYPE;
8850         }
8851     }
8852
8853     return 0;
8854 }
8855
8856 /* Parse a queue status request message into 'oqsr'.
8857  * Returns 0 if successful, otherwise an OFPERR_* number. */
8858 enum ofperr
8859 ofputil_decode_queue_stats_request(const struct ofp_header *request,
8860                                    struct ofputil_queue_stats_request *oqsr)
8861 {
8862     switch ((enum ofp_version)request->version) {
8863     case OFP15_VERSION:
8864     case OFP14_VERSION:
8865     case OFP13_VERSION:
8866     case OFP12_VERSION:
8867     case OFP11_VERSION: {
8868         const struct ofp11_queue_stats_request *qsr11 = ofpmsg_body(request);
8869         oqsr->queue_id = ntohl(qsr11->queue_id);
8870         return ofputil_port_from_ofp11(qsr11->port_no, &oqsr->port_no);
8871     }
8872
8873     case OFP10_VERSION: {
8874         const struct ofp10_queue_stats_request *qsr10 = ofpmsg_body(request);
8875         oqsr->queue_id = ntohl(qsr10->queue_id);
8876         oqsr->port_no = u16_to_ofp(ntohs(qsr10->port_no));
8877         /* OF 1.0 uses OFPP_ALL for OFPP_ANY */
8878         if (oqsr->port_no == OFPP_ALL) {
8879             oqsr->port_no = OFPP_ANY;
8880         }
8881         return 0;
8882     }
8883
8884     default:
8885         OVS_NOT_REACHED();
8886     }
8887 }
8888
8889 /* Encode a queue stats request for 'oqsr', the encoded message
8890  * will be for OpenFlow version 'ofp_version'. Returns message
8891  * as a struct ofpbuf. Returns encoded message on success, NULL on error. */
8892 struct ofpbuf *
8893 ofputil_encode_queue_stats_request(enum ofp_version ofp_version,
8894                                    const struct ofputil_queue_stats_request *oqsr)
8895 {
8896     struct ofpbuf *request;
8897
8898     switch (ofp_version) {
8899     case OFP11_VERSION:
8900     case OFP12_VERSION:
8901     case OFP13_VERSION:
8902     case OFP14_VERSION:
8903     case OFP15_VERSION: {
8904         struct ofp11_queue_stats_request *req;
8905         request = ofpraw_alloc(OFPRAW_OFPST11_QUEUE_REQUEST, ofp_version, 0);
8906         req = ofpbuf_put_zeros(request, sizeof *req);
8907         req->port_no = ofputil_port_to_ofp11(oqsr->port_no);
8908         req->queue_id = htonl(oqsr->queue_id);
8909         break;
8910     }
8911     case OFP10_VERSION: {
8912         struct ofp10_queue_stats_request *req;
8913         request = ofpraw_alloc(OFPRAW_OFPST10_QUEUE_REQUEST, ofp_version, 0);
8914         req = ofpbuf_put_zeros(request, sizeof *req);
8915         /* OpenFlow 1.0 needs OFPP_ALL instead of OFPP_ANY */
8916         req->port_no = htons(ofp_to_u16(oqsr->port_no == OFPP_ANY
8917                                         ? OFPP_ALL : oqsr->port_no));
8918         req->queue_id = htonl(oqsr->queue_id);
8919         break;
8920     }
8921     default:
8922         OVS_NOT_REACHED();
8923     }
8924
8925     return request;
8926 }
8927
8928 /* Returns the number of queue stats elements in OFPTYPE_QUEUE_STATS_REPLY
8929  * message 'oh'. */
8930 size_t
8931 ofputil_count_queue_stats(const struct ofp_header *oh)
8932 {
8933     struct ofpbuf b = ofpbuf_const_initializer(oh, ntohs(oh->length));
8934     ofpraw_pull_assert(&b);
8935
8936     for (size_t n = 0; ; n++) {
8937         struct ofputil_queue_stats qs;
8938         if (ofputil_decode_queue_stats(&qs, &b)) {
8939             return n;
8940         }
8941     }
8942 }
8943
8944 static enum ofperr
8945 ofputil_queue_stats_from_ofp10(struct ofputil_queue_stats *oqs,
8946                                const struct ofp10_queue_stats *qs10)
8947 {
8948     oqs->port_no = u16_to_ofp(ntohs(qs10->port_no));
8949     oqs->queue_id = ntohl(qs10->queue_id);
8950     oqs->tx_bytes = ntohll(get_32aligned_be64(&qs10->tx_bytes));
8951     oqs->tx_packets = ntohll(get_32aligned_be64(&qs10->tx_packets));
8952     oqs->tx_errors = ntohll(get_32aligned_be64(&qs10->tx_errors));
8953     oqs->duration_sec = oqs->duration_nsec = UINT32_MAX;
8954
8955     return 0;
8956 }
8957
8958 static enum ofperr
8959 ofputil_queue_stats_from_ofp11(struct ofputil_queue_stats *oqs,
8960                                const struct ofp11_queue_stats *qs11)
8961 {
8962     enum ofperr error;
8963
8964     error = ofputil_port_from_ofp11(qs11->port_no, &oqs->port_no);
8965     if (error) {
8966         return error;
8967     }
8968
8969     oqs->queue_id = ntohl(qs11->queue_id);
8970     oqs->tx_bytes = ntohll(qs11->tx_bytes);
8971     oqs->tx_packets = ntohll(qs11->tx_packets);
8972     oqs->tx_errors = ntohll(qs11->tx_errors);
8973     oqs->duration_sec = oqs->duration_nsec = UINT32_MAX;
8974
8975     return 0;
8976 }
8977
8978 static enum ofperr
8979 ofputil_queue_stats_from_ofp13(struct ofputil_queue_stats *oqs,
8980                                const struct ofp13_queue_stats *qs13)
8981 {
8982     enum ofperr error = ofputil_queue_stats_from_ofp11(oqs, &qs13->qs);
8983     if (!error) {
8984         oqs->duration_sec = ntohl(qs13->duration_sec);
8985         oqs->duration_nsec = ntohl(qs13->duration_nsec);
8986     }
8987
8988     return error;
8989 }
8990
8991 static enum ofperr
8992 ofputil_pull_ofp14_queue_stats(struct ofputil_queue_stats *oqs,
8993                                struct ofpbuf *msg)
8994 {
8995     const struct ofp14_queue_stats *qs14;
8996     size_t len;
8997
8998     qs14 = ofpbuf_try_pull(msg, sizeof *qs14);
8999     if (!qs14) {
9000         return OFPERR_OFPBRC_BAD_LEN;
9001     }
9002
9003     len = ntohs(qs14->length);
9004     if (len < sizeof *qs14 || len - sizeof *qs14 > msg->size) {
9005         return OFPERR_OFPBRC_BAD_LEN;
9006     }
9007     ofpbuf_pull(msg, len - sizeof *qs14);
9008
9009     /* No properties yet defined, so ignore them for now. */
9010
9011     return ofputil_queue_stats_from_ofp13(oqs, &qs14->qs);
9012 }
9013
9014 /* Converts an OFPST_QUEUE_STATS reply in 'msg' into an abstract
9015  * ofputil_queue_stats in 'qs'.
9016  *
9017  * Multiple OFPST_QUEUE_STATS replies can be packed into a single OpenFlow
9018  * message.  Calling this function multiple times for a single 'msg' iterates
9019  * through the replies.  The caller must initially leave 'msg''s layer pointers
9020  * null and not modify them between calls.
9021  *
9022  * Returns 0 if successful, EOF if no replies were left in this 'msg',
9023  * otherwise a positive errno value. */
9024 int
9025 ofputil_decode_queue_stats(struct ofputil_queue_stats *qs, struct ofpbuf *msg)
9026 {
9027     enum ofperr error;
9028     enum ofpraw raw;
9029
9030     error = (msg->header ? ofpraw_decode(&raw, msg->header)
9031              : ofpraw_pull(&raw, msg));
9032     if (error) {
9033         return error;
9034     }
9035
9036     if (!msg->size) {
9037         return EOF;
9038     } else if (raw == OFPRAW_OFPST14_QUEUE_REPLY) {
9039         return ofputil_pull_ofp14_queue_stats(qs, msg);
9040     } else if (raw == OFPRAW_OFPST13_QUEUE_REPLY) {
9041         const struct ofp13_queue_stats *qs13;
9042
9043         qs13 = ofpbuf_try_pull(msg, sizeof *qs13);
9044         if (!qs13) {
9045             goto bad_len;
9046         }
9047         return ofputil_queue_stats_from_ofp13(qs, qs13);
9048     } else if (raw == OFPRAW_OFPST11_QUEUE_REPLY) {
9049         const struct ofp11_queue_stats *qs11;
9050
9051         qs11 = ofpbuf_try_pull(msg, sizeof *qs11);
9052         if (!qs11) {
9053             goto bad_len;
9054         }
9055         return ofputil_queue_stats_from_ofp11(qs, qs11);
9056     } else if (raw == OFPRAW_OFPST10_QUEUE_REPLY) {
9057         const struct ofp10_queue_stats *qs10;
9058
9059         qs10 = ofpbuf_try_pull(msg, sizeof *qs10);
9060         if (!qs10) {
9061             goto bad_len;
9062         }
9063         return ofputil_queue_stats_from_ofp10(qs, qs10);
9064     } else {
9065         OVS_NOT_REACHED();
9066     }
9067
9068  bad_len:
9069     VLOG_WARN_RL(&bad_ofmsg_rl, "OFPST_QUEUE reply has %"PRIu32" leftover "
9070                  "bytes at end", msg->size);
9071     return OFPERR_OFPBRC_BAD_LEN;
9072 }
9073
9074 static void
9075 ofputil_queue_stats_to_ofp10(const struct ofputil_queue_stats *oqs,
9076                              struct ofp10_queue_stats *qs10)
9077 {
9078     qs10->port_no = htons(ofp_to_u16(oqs->port_no));
9079     memset(qs10->pad, 0, sizeof qs10->pad);
9080     qs10->queue_id = htonl(oqs->queue_id);
9081     put_32aligned_be64(&qs10->tx_bytes, htonll(oqs->tx_bytes));
9082     put_32aligned_be64(&qs10->tx_packets, htonll(oqs->tx_packets));
9083     put_32aligned_be64(&qs10->tx_errors, htonll(oqs->tx_errors));
9084 }
9085
9086 static void
9087 ofputil_queue_stats_to_ofp11(const struct ofputil_queue_stats *oqs,
9088                              struct ofp11_queue_stats *qs11)
9089 {
9090     qs11->port_no = ofputil_port_to_ofp11(oqs->port_no);
9091     qs11->queue_id = htonl(oqs->queue_id);
9092     qs11->tx_bytes = htonll(oqs->tx_bytes);
9093     qs11->tx_packets = htonll(oqs->tx_packets);
9094     qs11->tx_errors = htonll(oqs->tx_errors);
9095 }
9096
9097 static void
9098 ofputil_queue_stats_to_ofp13(const struct ofputil_queue_stats *oqs,
9099                              struct ofp13_queue_stats *qs13)
9100 {
9101     ofputil_queue_stats_to_ofp11(oqs, &qs13->qs);
9102     if (oqs->duration_sec != UINT32_MAX) {
9103         qs13->duration_sec = htonl(oqs->duration_sec);
9104         qs13->duration_nsec = htonl(oqs->duration_nsec);
9105     } else {
9106         qs13->duration_sec = OVS_BE32_MAX;
9107         qs13->duration_nsec = OVS_BE32_MAX;
9108     }
9109 }
9110
9111 static void
9112 ofputil_queue_stats_to_ofp14(const struct ofputil_queue_stats *oqs,
9113                              struct ofp14_queue_stats *qs14)
9114 {
9115     qs14->length = htons(sizeof *qs14);
9116     memset(qs14->pad, 0, sizeof qs14->pad);
9117     ofputil_queue_stats_to_ofp13(oqs, &qs14->qs);
9118 }
9119
9120
9121 /* Encode a queue stat for 'oqs' and append it to 'replies'. */
9122 void
9123 ofputil_append_queue_stat(struct ovs_list *replies,
9124                           const struct ofputil_queue_stats *oqs)
9125 {
9126     switch (ofpmp_version(replies)) {
9127     case OFP13_VERSION: {
9128         struct ofp13_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
9129         ofputil_queue_stats_to_ofp13(oqs, reply);
9130         break;
9131     }
9132
9133     case OFP12_VERSION:
9134     case OFP11_VERSION: {
9135         struct ofp11_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
9136         ofputil_queue_stats_to_ofp11(oqs, reply);
9137         break;
9138     }
9139
9140     case OFP10_VERSION: {
9141         struct ofp10_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
9142         ofputil_queue_stats_to_ofp10(oqs, reply);
9143         break;
9144     }
9145
9146     case OFP14_VERSION:
9147     case OFP15_VERSION: {
9148         struct ofp14_queue_stats *reply = ofpmp_append(replies, sizeof *reply);
9149         ofputil_queue_stats_to_ofp14(oqs, reply);
9150         break;
9151     }
9152
9153     default:
9154         OVS_NOT_REACHED();
9155     }
9156 }
9157
9158 enum ofperr
9159 ofputil_decode_bundle_ctrl(const struct ofp_header *oh,
9160                            struct ofputil_bundle_ctrl_msg *msg)
9161 {
9162     struct ofpbuf b = ofpbuf_const_initializer(oh, ntohs(oh->length));
9163     enum ofpraw raw = ofpraw_pull_assert(&b);
9164     ovs_assert(raw == OFPRAW_OFPT14_BUNDLE_CONTROL);
9165
9166     const struct ofp14_bundle_ctrl_msg *m = b.msg;
9167     msg->bundle_id = ntohl(m->bundle_id);
9168     msg->type = ntohs(m->type);
9169     msg->flags = ntohs(m->flags);
9170
9171     return 0;
9172 }
9173
9174 struct ofpbuf *
9175 ofputil_encode_bundle_ctrl_request(enum ofp_version ofp_version,
9176                                    struct ofputil_bundle_ctrl_msg *bc)
9177 {
9178     struct ofpbuf *request;
9179     struct ofp14_bundle_ctrl_msg *m;
9180
9181     switch (ofp_version) {
9182     case OFP10_VERSION:
9183     case OFP11_VERSION:
9184     case OFP12_VERSION:
9185     case OFP13_VERSION:
9186         ovs_fatal(0, "bundles need OpenFlow 1.4 or later "
9187                      "(\'-O OpenFlow14\')");
9188     case OFP14_VERSION:
9189     case OFP15_VERSION:
9190         request = ofpraw_alloc(OFPRAW_OFPT14_BUNDLE_CONTROL, ofp_version, 0);
9191         m = ofpbuf_put_zeros(request, sizeof *m);
9192
9193         m->bundle_id = htonl(bc->bundle_id);
9194         m->type = htons(bc->type);
9195         m->flags = htons(bc->flags);
9196         break;
9197     default:
9198         OVS_NOT_REACHED();
9199     }
9200
9201     return request;
9202 }
9203
9204 struct ofpbuf *
9205 ofputil_encode_bundle_ctrl_reply(const struct ofp_header *oh,
9206                                  struct ofputil_bundle_ctrl_msg *msg)
9207 {
9208     struct ofpbuf *buf;
9209     struct ofp14_bundle_ctrl_msg *m;
9210
9211     buf = ofpraw_alloc_reply(OFPRAW_OFPT14_BUNDLE_CONTROL, oh, 0);
9212     m = ofpbuf_put_zeros(buf, sizeof *m);
9213
9214     m->bundle_id = htonl(msg->bundle_id);
9215     m->type = htons(msg->type);
9216     m->flags = htons(msg->flags);
9217
9218     return buf;
9219 }
9220
9221 /* Return true for bundlable state change requests, false for other messages.
9222  */
9223 static bool
9224 ofputil_is_bundlable(enum ofptype type)
9225 {
9226     switch (type) {
9227         /* Minimum required by OpenFlow 1.4. */
9228     case OFPTYPE_PORT_MOD:
9229     case OFPTYPE_FLOW_MOD:
9230         return true;
9231
9232         /* Nice to have later. */
9233     case OFPTYPE_FLOW_MOD_TABLE_ID:
9234     case OFPTYPE_GROUP_MOD:
9235     case OFPTYPE_TABLE_MOD:
9236     case OFPTYPE_METER_MOD:
9237     case OFPTYPE_PACKET_OUT:
9238     case OFPTYPE_NXT_TLV_TABLE_MOD:
9239
9240         /* Not to be bundlable. */
9241     case OFPTYPE_ECHO_REQUEST:
9242     case OFPTYPE_FEATURES_REQUEST:
9243     case OFPTYPE_GET_CONFIG_REQUEST:
9244     case OFPTYPE_SET_CONFIG:
9245     case OFPTYPE_BARRIER_REQUEST:
9246     case OFPTYPE_ROLE_REQUEST:
9247     case OFPTYPE_ECHO_REPLY:
9248     case OFPTYPE_SET_FLOW_FORMAT:
9249     case OFPTYPE_SET_PACKET_IN_FORMAT:
9250     case OFPTYPE_SET_CONTROLLER_ID:
9251     case OFPTYPE_FLOW_AGE:
9252     case OFPTYPE_FLOW_MONITOR_CANCEL:
9253     case OFPTYPE_SET_ASYNC_CONFIG:
9254     case OFPTYPE_GET_ASYNC_REQUEST:
9255     case OFPTYPE_DESC_STATS_REQUEST:
9256     case OFPTYPE_FLOW_STATS_REQUEST:
9257     case OFPTYPE_AGGREGATE_STATS_REQUEST:
9258     case OFPTYPE_TABLE_STATS_REQUEST:
9259     case OFPTYPE_TABLE_FEATURES_STATS_REQUEST:
9260     case OFPTYPE_TABLE_DESC_REQUEST:
9261     case OFPTYPE_PORT_STATS_REQUEST:
9262     case OFPTYPE_QUEUE_STATS_REQUEST:
9263     case OFPTYPE_PORT_DESC_STATS_REQUEST:
9264     case OFPTYPE_FLOW_MONITOR_STATS_REQUEST:
9265     case OFPTYPE_METER_STATS_REQUEST:
9266     case OFPTYPE_METER_CONFIG_STATS_REQUEST:
9267     case OFPTYPE_METER_FEATURES_STATS_REQUEST:
9268     case OFPTYPE_GROUP_STATS_REQUEST:
9269     case OFPTYPE_GROUP_DESC_STATS_REQUEST:
9270     case OFPTYPE_GROUP_FEATURES_STATS_REQUEST:
9271     case OFPTYPE_QUEUE_GET_CONFIG_REQUEST:
9272     case OFPTYPE_BUNDLE_CONTROL:
9273     case OFPTYPE_BUNDLE_ADD_MESSAGE:
9274     case OFPTYPE_HELLO:
9275     case OFPTYPE_ERROR:
9276     case OFPTYPE_FEATURES_REPLY:
9277     case OFPTYPE_GET_CONFIG_REPLY:
9278     case OFPTYPE_PACKET_IN:
9279     case OFPTYPE_FLOW_REMOVED:
9280     case OFPTYPE_PORT_STATUS:
9281     case OFPTYPE_BARRIER_REPLY:
9282     case OFPTYPE_QUEUE_GET_CONFIG_REPLY:
9283     case OFPTYPE_DESC_STATS_REPLY:
9284     case OFPTYPE_FLOW_STATS_REPLY:
9285     case OFPTYPE_QUEUE_STATS_REPLY:
9286     case OFPTYPE_PORT_STATS_REPLY:
9287     case OFPTYPE_TABLE_STATS_REPLY:
9288     case OFPTYPE_AGGREGATE_STATS_REPLY:
9289     case OFPTYPE_PORT_DESC_STATS_REPLY:
9290     case OFPTYPE_ROLE_REPLY:
9291     case OFPTYPE_FLOW_MONITOR_PAUSED:
9292     case OFPTYPE_FLOW_MONITOR_RESUMED:
9293     case OFPTYPE_FLOW_MONITOR_STATS_REPLY:
9294     case OFPTYPE_GET_ASYNC_REPLY:
9295     case OFPTYPE_GROUP_STATS_REPLY:
9296     case OFPTYPE_GROUP_DESC_STATS_REPLY:
9297     case OFPTYPE_GROUP_FEATURES_STATS_REPLY:
9298     case OFPTYPE_METER_STATS_REPLY:
9299     case OFPTYPE_METER_CONFIG_STATS_REPLY:
9300     case OFPTYPE_METER_FEATURES_STATS_REPLY:
9301     case OFPTYPE_TABLE_FEATURES_STATS_REPLY:
9302     case OFPTYPE_TABLE_DESC_REPLY:
9303     case OFPTYPE_ROLE_STATUS:
9304     case OFPTYPE_REQUESTFORWARD:
9305     case OFPTYPE_NXT_TLV_TABLE_REQUEST:
9306     case OFPTYPE_NXT_TLV_TABLE_REPLY:
9307         break;
9308     }
9309
9310     return false;
9311 }
9312
9313 enum ofperr
9314 ofputil_decode_bundle_add(const struct ofp_header *oh,
9315                           struct ofputil_bundle_add_msg *msg,
9316                           enum ofptype *typep)
9317 {
9318     struct ofpbuf b = ofpbuf_const_initializer(oh, ntohs(oh->length));
9319     enum ofpraw raw = ofpraw_pull_assert(&b);
9320     ovs_assert(raw == OFPRAW_OFPT14_BUNDLE_ADD_MESSAGE);
9321
9322     const struct ofp14_bundle_ctrl_msg *m = ofpbuf_pull(&b, sizeof *m);
9323     msg->bundle_id = ntohl(m->bundle_id);
9324     msg->flags = ntohs(m->flags);
9325
9326     msg->msg = b.data;
9327     if (msg->msg->version != oh->version) {
9328         return OFPERR_NXBFC_BAD_VERSION;
9329     }
9330     size_t inner_len = ntohs(msg->msg->length);
9331     if (inner_len < sizeof(struct ofp_header) || inner_len > b.size) {
9332         return OFPERR_OFPBFC_MSG_BAD_LEN;
9333     }
9334     if (msg->msg->xid != oh->xid) {
9335         return OFPERR_OFPBFC_MSG_BAD_XID;
9336     }
9337
9338     /* Reject unbundlable messages. */
9339     enum ofptype type;
9340     enum ofperr error = ofptype_decode(&type, msg->msg);
9341     if (error) {
9342         VLOG_WARN_RL(&bad_ofmsg_rl, "OFPT14_BUNDLE_ADD_MESSAGE contained "
9343                      "message is unparsable (%s)", ofperr_get_name(error));
9344         return OFPERR_OFPBFC_MSG_UNSUP; /* 'error' would be confusing. */
9345     }
9346
9347     if (!ofputil_is_bundlable(type)) {
9348         VLOG_WARN_RL(&bad_ofmsg_rl, "%s message not allowed inside "
9349                      "OFPT14_BUNDLE_ADD_MESSAGE", ofptype_get_name(type));
9350         return OFPERR_OFPBFC_MSG_UNSUP;
9351     }
9352     if (typep) {
9353         *typep = type;
9354     }
9355
9356     return 0;
9357 }
9358
9359 struct ofpbuf *
9360 ofputil_encode_bundle_add(enum ofp_version ofp_version,
9361                           struct ofputil_bundle_add_msg *msg)
9362 {
9363     struct ofpbuf *request;
9364     struct ofp14_bundle_ctrl_msg *m;
9365
9366     /* Must use the same xid as the embedded message. */
9367     request = ofpraw_alloc_xid(OFPRAW_OFPT14_BUNDLE_ADD_MESSAGE, ofp_version,
9368                                msg->msg->xid, 0);
9369     m = ofpbuf_put_zeros(request, sizeof *m);
9370
9371     m->bundle_id = htonl(msg->bundle_id);
9372     m->flags = htons(msg->flags);
9373     ofpbuf_put(request, msg->msg, ntohs(msg->msg->length));
9374
9375     return request;
9376 }
9377
9378 static void
9379 encode_tlv_table_mappings(struct ofpbuf *b, struct ovs_list *mappings)
9380 {
9381     struct ofputil_tlv_map *map;
9382
9383     LIST_FOR_EACH (map, list_node, mappings) {
9384         struct nx_tlv_map *nx_map;
9385
9386         nx_map = ofpbuf_put_zeros(b, sizeof *nx_map);
9387         nx_map->option_class = htons(map->option_class);
9388         nx_map->option_type = map->option_type;
9389         nx_map->option_len = map->option_len;
9390         nx_map->index = htons(map->index);
9391     }
9392 }
9393
9394 struct ofpbuf *
9395 ofputil_encode_tlv_table_mod(enum ofp_version ofp_version,
9396                                 struct ofputil_tlv_table_mod *ttm)
9397 {
9398     struct ofpbuf *b;
9399     struct nx_tlv_table_mod *nx_ttm;
9400
9401     b = ofpraw_alloc(OFPRAW_NXT_TLV_TABLE_MOD, ofp_version, 0);
9402     nx_ttm = ofpbuf_put_zeros(b, sizeof *nx_ttm);
9403     nx_ttm->command = htons(ttm->command);
9404     encode_tlv_table_mappings(b, &ttm->mappings);
9405
9406     return b;
9407 }
9408
9409 static enum ofperr
9410 decode_tlv_table_mappings(struct ofpbuf *msg, unsigned int max_fields,
9411                              struct ovs_list *mappings)
9412 {
9413     list_init(mappings);
9414
9415     while (msg->size) {
9416         struct nx_tlv_map *nx_map;
9417         struct ofputil_tlv_map *map;
9418
9419         nx_map = ofpbuf_pull(msg, sizeof *nx_map);
9420         map = xmalloc(sizeof *map);
9421         list_push_back(mappings, &map->list_node);
9422
9423         map->option_class = ntohs(nx_map->option_class);
9424         map->option_type = nx_map->option_type;
9425
9426         map->option_len = nx_map->option_len;
9427         if (map->option_len % 4 || map->option_len > TLV_MAX_OPT_SIZE) {
9428             VLOG_WARN_RL(&bad_ofmsg_rl,
9429                          "tlv table option length (%u) is not a valid option size",
9430                          map->option_len);
9431             ofputil_uninit_tlv_table(mappings);
9432             return OFPERR_NXTTMFC_BAD_OPT_LEN;
9433         }
9434
9435         map->index = ntohs(nx_map->index);
9436         if (map->index >= max_fields) {
9437             VLOG_WARN_RL(&bad_ofmsg_rl,
9438                          "tlv table field index (%u) is too large (max %u)",
9439                          map->index, max_fields - 1);
9440             ofputil_uninit_tlv_table(mappings);
9441             return OFPERR_NXTTMFC_BAD_FIELD_IDX;
9442         }
9443     }
9444
9445     return 0;
9446 }
9447
9448 enum ofperr
9449 ofputil_decode_tlv_table_mod(const struct ofp_header *oh,
9450                                 struct ofputil_tlv_table_mod *ttm)
9451 {
9452     struct ofpbuf msg = ofpbuf_const_initializer(oh, ntohs(oh->length));
9453     ofpraw_pull_assert(&msg);
9454
9455     struct nx_tlv_table_mod *nx_ttm = ofpbuf_pull(&msg, sizeof *nx_ttm);
9456     ttm->command = ntohs(nx_ttm->command);
9457     if (ttm->command > NXTTMC_CLEAR) {
9458         VLOG_WARN_RL(&bad_ofmsg_rl,
9459                      "tlv table mod command (%u) is out of range",
9460                      ttm->command);
9461         return OFPERR_NXTTMFC_BAD_COMMAND;
9462     }
9463
9464     return decode_tlv_table_mappings(&msg, TUN_METADATA_NUM_OPTS,
9465                                         &ttm->mappings);
9466 }
9467
9468 struct ofpbuf *
9469 ofputil_encode_tlv_table_reply(const struct ofp_header *oh,
9470                                   struct ofputil_tlv_table_reply *ttr)
9471 {
9472     struct ofpbuf *b;
9473     struct nx_tlv_table_reply *nx_ttr;
9474
9475     b = ofpraw_alloc_reply(OFPRAW_NXT_TLV_TABLE_REPLY, oh, 0);
9476     nx_ttr = ofpbuf_put_zeros(b, sizeof *nx_ttr);
9477     nx_ttr->max_option_space = htonl(ttr->max_option_space);
9478     nx_ttr->max_fields = htons(ttr->max_fields);
9479
9480     encode_tlv_table_mappings(b, &ttr->mappings);
9481
9482     return b;
9483 }
9484
9485 /* Decodes the NXT_TLV_TABLE_REPLY message in 'oh' into '*ttr'.  Returns 0
9486  * if successful, otherwise an ofperr.
9487  *
9488  * The decoder verifies that the indexes in 'ttr->mappings' are less than
9489  * 'ttr->max_fields', but the caller must ensure, if necessary, that they are
9490  * less than TUN_METADATA_NUM_OPTS. */
9491 enum ofperr
9492 ofputil_decode_tlv_table_reply(const struct ofp_header *oh,
9493                                   struct ofputil_tlv_table_reply *ttr)
9494 {
9495     struct ofpbuf msg = ofpbuf_const_initializer(oh, ntohs(oh->length));
9496     ofpraw_pull_assert(&msg);
9497
9498     struct nx_tlv_table_reply *nx_ttr = ofpbuf_pull(&msg, sizeof *nx_ttr);
9499     ttr->max_option_space = ntohl(nx_ttr->max_option_space);
9500     ttr->max_fields = ntohs(nx_ttr->max_fields);
9501
9502     return decode_tlv_table_mappings(&msg, ttr->max_fields, &ttr->mappings);
9503 }
9504
9505 void
9506 ofputil_uninit_tlv_table(struct ovs_list *mappings)
9507 {
9508     struct ofputil_tlv_map *map;
9509
9510     LIST_FOR_EACH_POP (map, list_node, mappings) {
9511         free(map);
9512     }
9513 }
9514
9515 const char *
9516 ofputil_async_msg_type_to_string(enum ofputil_async_msg_type type)
9517 {
9518     switch (type) {
9519     case OAM_PACKET_IN:      return "PACKET_IN";
9520     case OAM_PORT_STATUS:    return "PORT_STATUS";
9521     case OAM_FLOW_REMOVED:   return "FLOW_REMOVED";
9522     case OAM_ROLE_STATUS:    return "ROLE_STATUS";
9523     case OAM_TABLE_STATUS:   return "TABLE_STATUS";
9524     case OAM_REQUESTFORWARD: return "REQUESTFORWARD";
9525
9526     case OAM_N_TYPES:
9527     default:
9528         OVS_NOT_REACHED();
9529     }
9530 }
9531
9532 struct ofp14_async_prop {
9533     uint64_t prop_type;
9534     enum ofputil_async_msg_type oam;
9535     bool master;
9536     uint32_t allowed10, allowed14;
9537 };
9538
9539 #define AP_PAIR(SLAVE_PROP_TYPE, OAM, A10, A14) \
9540     { SLAVE_PROP_TYPE,       OAM, false, A10, (A14) ? (A14) : (A10) },  \
9541     { (SLAVE_PROP_TYPE + 1), OAM, true,  A10, (A14) ? (A14) : (A10) }
9542
9543 static const struct ofp14_async_prop async_props[] = {
9544     AP_PAIR( 0, OAM_PACKET_IN,      OFPR10_BITS, OFPR14_BITS),
9545     AP_PAIR( 2, OAM_PORT_STATUS,    (1 << OFPPR_N_REASONS) - 1, 0),
9546     AP_PAIR( 4, OAM_FLOW_REMOVED,   (1 << OVS_OFPRR_NONE) - 1, 0),
9547     AP_PAIR( 6, OAM_ROLE_STATUS,    (1 << OFPCRR_N_REASONS) - 1, 0),
9548     AP_PAIR( 8, OAM_TABLE_STATUS,   OFPTR_BITS, 0),
9549     AP_PAIR(10, OAM_REQUESTFORWARD, (1 << OFPRFR_N_REASONS) - 1, 0),
9550 };
9551
9552 #define FOR_EACH_ASYNC_PROP(VAR)                                \
9553     for (const struct ofp14_async_prop *VAR = async_props;      \
9554          VAR < &async_props[ARRAY_SIZE(async_props)]; VAR++)
9555
9556 static const struct ofp14_async_prop *
9557 get_ofp14_async_config_prop_by_prop_type(uint64_t prop_type)
9558 {
9559     FOR_EACH_ASYNC_PROP (ap) {
9560         if (prop_type == ap->prop_type) {
9561             return ap;
9562         }
9563     }
9564     return NULL;
9565 }
9566
9567 static const struct ofp14_async_prop *
9568 get_ofp14_async_config_prop_by_oam(enum ofputil_async_msg_type oam,
9569                                    bool master)
9570 {
9571     FOR_EACH_ASYNC_PROP (ap) {
9572         if (ap->oam == oam && ap->master == master) {
9573             return ap;
9574         }
9575     }
9576     return NULL;
9577 }
9578
9579 static uint32_t
9580 ofp14_async_prop_allowed(const struct ofp14_async_prop *prop,
9581                          enum ofp_version version)
9582 {
9583     return version >= OFP14_VERSION ? prop->allowed14 : prop->allowed10;
9584 }
9585
9586 static ovs_be32
9587 encode_async_mask(const struct ofputil_async_cfg *src,
9588                   const struct ofp14_async_prop *ap,
9589                   enum ofp_version version)
9590 {
9591     uint32_t mask = ap->master ? src->master[ap->oam] : src->slave[ap->oam];
9592     return htonl(mask & ofp14_async_prop_allowed(ap, version));
9593 }
9594
9595 static enum ofperr
9596 decode_async_mask(ovs_be32 src,
9597                   const struct ofp14_async_prop *ap, enum ofp_version version,
9598                   bool loose, struct ofputil_async_cfg *dst)
9599 {
9600     uint32_t mask = ntohl(src);
9601     uint32_t allowed = ofp14_async_prop_allowed(ap, version);
9602     if (mask & ~allowed) {
9603         OFPPROP_LOG(&bad_ofmsg_rl, loose,
9604                     "bad value %#x for %s (allowed mask %#x)",
9605                     mask, ofputil_async_msg_type_to_string(ap->oam),
9606                     allowed);
9607         mask &= allowed;
9608         if (!loose) {
9609             return OFPERR_OFPACFC_INVALID;
9610         }
9611     }
9612
9613     if (ap->oam == OAM_PACKET_IN) {
9614         if (mask & (1u << OFPR_NO_MATCH)) {
9615             mask |= 1u << OFPR_EXPLICIT_MISS;
9616             if (version < OFP13_VERSION) {
9617                 mask |= 1u << OFPR_IMPLICIT_MISS;
9618             }
9619         }
9620     }
9621
9622     uint32_t *array = ap->master ? dst->master : dst->slave;
9623     array[ap->oam] = mask;
9624     return 0;
9625 }
9626
9627 static enum ofperr
9628 parse_async_tlv(const struct ofpbuf *property,
9629                 const struct ofp14_async_prop *ap,
9630                 struct ofputil_async_cfg *ac,
9631                 enum ofp_version version, bool loose)
9632 {
9633     enum ofperr error;
9634     ovs_be32 mask;
9635
9636     error  = ofpprop_parse_be32(property, &mask);
9637     if (error) {
9638         return error;
9639     }
9640
9641     if (ofpprop_is_experimenter(ap->prop_type)) {
9642         /* For experimenter properties, whether a property is for the master or
9643          * slave role is indicated by both 'type' and 'exp_type' in struct
9644          * ofp_prop_experimenter.  Check that these are consistent. */
9645         const struct ofp_prop_experimenter *ope = property->data;
9646         bool should_be_master = ope->type == htons(0xffff);
9647         if (should_be_master != ap->master) {
9648             VLOG_WARN_RL(&bad_ofmsg_rl, "async property type %#"PRIx16" "
9649                          "indicates %s role but exp_type %"PRIu32" indicates "
9650                          "%s role",
9651                          ntohs(ope->type),
9652                          should_be_master ? "master" : "slave",
9653                          ntohl(ope->exp_type),
9654                          ap->master ? "master" : "slave");
9655             return OFPERR_OFPBPC_BAD_EXP_TYPE;
9656         }
9657     }
9658
9659     return decode_async_mask(mask, ap, version, loose, ac);
9660 }
9661
9662 static void
9663 decode_legacy_async_masks(const ovs_be32 masks[2],
9664                           enum ofputil_async_msg_type oam,
9665                           enum ofp_version version,
9666                           struct ofputil_async_cfg *dst)
9667 {
9668     for (int i = 0; i < 2; i++) {
9669         bool master = i == 0;
9670         const struct ofp14_async_prop *ap
9671             = get_ofp14_async_config_prop_by_oam(oam, master);
9672         decode_async_mask(masks[i], ap, version, true, dst);
9673     }
9674 }
9675
9676 /* Decodes the OpenFlow "set async config" request and "get async config
9677  * reply" message in '*oh' into an abstract form in 'ac'.
9678  *
9679  * Some versions of the "set async config" request change only some of the
9680  * settings and leave the others alone.  This function uses 'basis' as the
9681  * initial state for decoding these.  Other versions of the request change all
9682  * the settings; this function ignores 'basis' when decoding these.
9683  *
9684  * If 'loose' is true, this function ignores properties and values that it does
9685  * not understand, as a controller would want to do when interpreting
9686  * capabilities provided by a switch.  If 'loose' is false, this function
9687  * treats unknown properties and values as an error, as a switch would want to
9688  * do when interpreting a configuration request made by a controller.
9689  *
9690  * Returns 0 if successful, otherwise an OFPERR_* value.
9691  *
9692  * Returns error code OFPERR_OFPACFC_INVALID if the value of mask is not in
9693  * the valid range of mask.
9694  *
9695  * Returns error code OFPERR_OFPACFC_UNSUPPORTED if the configuration is not
9696  * supported.*/
9697 enum ofperr
9698 ofputil_decode_set_async_config(const struct ofp_header *oh, bool loose,
9699                                 const struct ofputil_async_cfg *basis,
9700                                 struct ofputil_async_cfg *ac)
9701 {
9702     struct ofpbuf b = ofpbuf_const_initializer(oh, ntohs(oh->length));
9703     enum ofpraw raw = ofpraw_pull_assert(&b);
9704
9705     if (raw == OFPRAW_OFPT13_SET_ASYNC ||
9706         raw == OFPRAW_NXT_SET_ASYNC_CONFIG ||
9707         raw == OFPRAW_OFPT13_GET_ASYNC_REPLY) {
9708         const struct nx_async_config *msg = ofpmsg_body(oh);
9709
9710         *ac = OFPUTIL_ASYNC_CFG_INIT;
9711         decode_legacy_async_masks(msg->packet_in_mask, OAM_PACKET_IN,
9712                                   oh->version, ac);
9713         decode_legacy_async_masks(msg->port_status_mask, OAM_PORT_STATUS,
9714                                   oh->version, ac);
9715         decode_legacy_async_masks(msg->flow_removed_mask, OAM_FLOW_REMOVED,
9716                                   oh->version, ac);
9717     } else if (raw == OFPRAW_OFPT14_SET_ASYNC ||
9718                raw == OFPRAW_OFPT14_GET_ASYNC_REPLY ||
9719                raw == OFPRAW_NXT_SET_ASYNC_CONFIG2) {
9720         *ac = *basis;
9721         while (b.size > 0) {
9722             struct ofpbuf property;
9723             enum ofperr error;
9724             uint64_t type;
9725
9726             error = ofpprop_pull__(&b, &property, 8, 0xfffe, &type);
9727             if (error) {
9728                 return error;
9729             }
9730
9731             const struct ofp14_async_prop *ap
9732                 = get_ofp14_async_config_prop_by_prop_type(type);
9733             error = (ap
9734                      ? parse_async_tlv(&property, ap, ac, oh->version, loose)
9735                      : OFPPROP_UNKNOWN(loose, "async config", type));
9736             if (error) {
9737                 /* Most messages use OFPBPC_BAD_TYPE but async has its own (who
9738                  * knows why, it's OpenFlow. */
9739                 if (error == OFPERR_OFPBPC_BAD_TYPE) {
9740                     error = OFPERR_OFPACFC_UNSUPPORTED;
9741                 }
9742                 return error;
9743             }
9744         }
9745     } else {
9746         return OFPERR_OFPBRC_BAD_VERSION;
9747     }
9748     return 0;
9749 }
9750
9751 static void
9752 encode_legacy_async_masks(const struct ofputil_async_cfg *ac,
9753                           enum ofputil_async_msg_type oam,
9754                           enum ofp_version version,
9755                           ovs_be32 masks[2])
9756 {
9757     for (int i = 0; i < 2; i++) {
9758         bool master = i == 0;
9759         const struct ofp14_async_prop *ap
9760             = get_ofp14_async_config_prop_by_oam(oam, master);
9761         masks[i] = encode_async_mask(ac, ap, version);
9762     }
9763 }
9764
9765 static void
9766 ofputil_put_async_config__(const struct ofputil_async_cfg *ac,
9767                            struct ofpbuf *buf, bool tlv,
9768                            enum ofp_version version, uint32_t oams)
9769 {
9770     if (!tlv) {
9771         struct nx_async_config *msg = ofpbuf_put_zeros(buf, sizeof *msg);
9772         encode_legacy_async_masks(ac, OAM_PACKET_IN, version,
9773                                   msg->packet_in_mask);
9774         encode_legacy_async_masks(ac, OAM_PORT_STATUS, version,
9775                                   msg->port_status_mask);
9776         encode_legacy_async_masks(ac, OAM_FLOW_REMOVED, version,
9777                                   msg->flow_removed_mask);
9778     } else {
9779         FOR_EACH_ASYNC_PROP (ap) {
9780             if (oams & (1u << ap->oam)) {
9781                 size_t ofs = buf->size;
9782                 ofpprop_put_be32(buf, ap->prop_type,
9783                                  encode_async_mask(ac, ap, version));
9784
9785                 /* For experimenter properties, we need to use type 0xfffe for
9786                  * master and 0xffff for slaves. */
9787                 if (ofpprop_is_experimenter(ap->prop_type)) {
9788                     struct ofp_prop_experimenter *ope
9789                         = ofpbuf_at_assert(buf, ofs, sizeof *ope);
9790                     ope->type = ap->master ? htons(0xffff) : htons(0xfffe);
9791                 }
9792             }
9793         }
9794     }
9795 }
9796
9797 /* Encodes and returns a reply to the OFPT_GET_ASYNC_REQUEST in 'oh' that
9798  * states that the asynchronous message configuration is 'ac'. */
9799 struct ofpbuf *
9800 ofputil_encode_get_async_reply(const struct ofp_header *oh,
9801                                const struct ofputil_async_cfg *ac)
9802 {
9803     struct ofpbuf *buf;
9804
9805     enum ofpraw raw = (oh->version < OFP14_VERSION
9806                        ? OFPRAW_OFPT13_GET_ASYNC_REPLY
9807                        : OFPRAW_OFPT14_GET_ASYNC_REPLY);
9808     struct ofpbuf *reply = ofpraw_alloc_reply(raw, oh, 0);
9809     ofputil_put_async_config__(ac, reply,
9810                                raw == OFPRAW_OFPT14_GET_ASYNC_REPLY,
9811                                oh->version, UINT32_MAX);
9812     return reply;
9813
9814     return buf;
9815 }
9816
9817 /* Encodes and returns a message, in a format appropriate for OpenFlow version
9818  * 'ofp_version', that sets the asynchronous message configuration to 'ac'.
9819  *
9820  * Specify 'oams' as a bitmap of OAM_* that indicate the asynchronous messages
9821  * to configure.  OF1.0 through OF1.3 can't natively configure a subset of
9822  * messages, so more messages than requested may be configured.  OF1.0 through
9823  * OF1.3 also can't configure OVS extension OAM_* values, so if 'oam' includes
9824  * any extensions then this function encodes an Open vSwitch extension message
9825  * that does support configuring OVS extension OAM_*. */
9826 struct ofpbuf *
9827 ofputil_encode_set_async_config(const struct ofputil_async_cfg *ac,
9828                                 uint32_t oams, enum ofp_version ofp_version)
9829 {
9830     enum ofpraw raw = (ofp_version >= OFP14_VERSION ? OFPRAW_OFPT14_SET_ASYNC
9831                        : oams & OAM_EXTENSIONS ? OFPRAW_NXT_SET_ASYNC_CONFIG2
9832                        : ofp_version >= OFP13_VERSION ? OFPRAW_OFPT13_SET_ASYNC
9833                        : OFPRAW_NXT_SET_ASYNC_CONFIG);
9834     struct ofpbuf *request = ofpraw_alloc(raw, ofp_version, 0);
9835     ofputil_put_async_config__(ac, request,
9836                                (raw == OFPRAW_OFPT14_SET_ASYNC ||
9837                                 raw == OFPRAW_NXT_SET_ASYNC_CONFIG2),
9838                                ofp_version, oams);
9839     return request;
9840 }
9841
9842 struct ofputil_async_cfg
9843 ofputil_async_cfg_default(enum ofp_version version)
9844 {
9845     /* We enable all of the OF1.4 reasons regardless of 'version' because the
9846      * reasons added in OF1.4 just are just refinements of the OFPR_ACTION
9847      * introduced in OF1.0, breaking it into more specific categories.  When we
9848      * encode these for earlier OpenFlow versions, we translate them into
9849      * OFPR_ACTION.  */
9850     uint32_t pin = OFPR14_BITS & ~(1u << OFPR_INVALID_TTL);
9851     pin |= 1u << OFPR_EXPLICIT_MISS;
9852     if (version <= OFP12_VERSION) {
9853         pin |= 1u << OFPR_IMPLICIT_MISS;
9854     }
9855
9856     return (struct ofputil_async_cfg) {
9857         .master[OAM_PACKET_IN] = pin,
9858
9859         .master[OAM_FLOW_REMOVED]
9860             = (version >= OFP14_VERSION ? OFPRR14_BITS : OFPRR10_BITS),
9861
9862         .master[OAM_PORT_STATUS] = OFPPR_BITS,
9863         .slave[OAM_PORT_STATUS] = OFPPR_BITS,
9864     };
9865 }