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